2008-07-17 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                 readonly OpCode op;
2088                 
2089                 public OpcodeCast (Expression child, Type return_type, OpCode op)
2090                         : base (child, return_type)
2091                 {
2092                         this.op = op;
2093                 }
2094
2095                 public override Expression DoResolve (EmitContext ec)
2096                 {
2097                         // This should never be invoked, we are born in fully
2098                         // initialized state.
2099
2100                         return this;
2101                 }
2102
2103                 public override void Emit (EmitContext ec)
2104                 {
2105                         base.Emit (ec);
2106                         ec.ig.Emit (op);
2107                 }
2108
2109                 public Type UnderlyingType {
2110                         get { return child.Type; }
2111                 }
2112         }
2113
2114         /// <summary>
2115         ///   This kind of cast is used to encapsulate a child and cast it
2116         ///   to the class requested
2117         /// </summary>
2118         public sealed class ClassCast : TypeCast {
2119                 Type child_generic_parameter;
2120
2121                 public ClassCast (Expression child, Type return_type)
2122                         : base (child, return_type)
2123                         
2124                 {
2125                         if (TypeManager.IsGenericParameter (child.Type))
2126                                 child_generic_parameter = child.Type;
2127                 }
2128
2129                 public override Expression DoResolve (EmitContext ec)
2130                 {
2131                         // This should never be invoked, we are born in fully
2132                         // initialized state.
2133
2134                         return this;
2135                 }
2136
2137                 public override void Emit (EmitContext ec)
2138                 {
2139                         base.Emit (ec);
2140
2141                         if (child_generic_parameter != null)
2142                                 ec.ig.Emit (OpCodes.Box, child_generic_parameter);
2143
2144 #if GMCS_SOURCE
2145                         if (type.IsGenericParameter)
2146                                 ec.ig.Emit (OpCodes.Unbox_Any, type);
2147                         else
2148 #endif
2149                                 ec.ig.Emit (OpCodes.Castclass, type);
2150                 }
2151
2152                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2153                 {
2154                         type = storey.MutateType (type);
2155                         if (child_generic_parameter != null)
2156                                 child_generic_parameter = storey.MutateGenericArgument (child_generic_parameter);
2157
2158                         base.MutateHoistedGenericType (storey);
2159                 }
2160         }
2161
2162         //
2163         // Used when resolved expression has different representations for
2164         // expression trees and emit phase
2165         //
2166         public class ReducedExpression : Expression
2167         {
2168                 class ReducedConstantExpression : Constant
2169                 {
2170                         readonly Constant expr;
2171                         readonly Expression orig_expr;
2172
2173                         public ReducedConstantExpression (Constant expr, Expression orig_expr)
2174                                 : base (expr.Location)
2175                         {
2176                                 this.expr = expr;
2177                                 this.orig_expr = orig_expr;
2178                                 eclass = expr.eclass;
2179                                 type = expr.Type;
2180                         }
2181
2182                         public override string AsString ()
2183                         {
2184                                 return expr.AsString ();
2185                         }
2186
2187                         public override Expression CreateExpressionTree (EmitContext ec)
2188                         {
2189                                 return orig_expr.CreateExpressionTree (ec);
2190                         }
2191
2192                         public override object GetValue ()
2193                         {
2194                                 return expr.GetValue ();
2195                         }
2196
2197                         public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
2198                         {
2199                                 throw new NotImplementedException ();
2200                         }
2201
2202                         public override Expression DoResolve (EmitContext ec)
2203                         {
2204                                 return this;
2205                         }
2206
2207                         public override Constant Increment ()
2208                         {
2209                                 throw new NotImplementedException ();
2210                         }
2211
2212                         public override bool IsDefaultValue {
2213                                 get {
2214                                         return expr.IsDefaultValue;
2215                                 }
2216                         }
2217
2218                         public override bool IsNegative {
2219                                 get {
2220                                         return expr.IsNegative;
2221                                 }
2222                         }
2223
2224                         public override void Emit (EmitContext ec)
2225                         {
2226                                 expr.Emit (ec);
2227                         }
2228                 }
2229
2230                 readonly Expression expr, orig_expr;
2231
2232                 private ReducedExpression (Expression expr, Expression orig_expr)
2233                 {
2234                         this.expr = expr;
2235                         this.orig_expr = orig_expr;
2236                         this.loc = orig_expr.Location;
2237                 }
2238
2239                 public static Expression Create (Constant expr, Expression original_expr)
2240                 {
2241                         return new ReducedConstantExpression (expr, original_expr);
2242                 }
2243
2244                 public static Expression Create (Expression expr, Expression original_expr)
2245                 {
2246                         Constant c = expr as Constant;
2247                         if (c != null)
2248                                 return Create (c, original_expr);
2249
2250                         return new ReducedExpression (expr, original_expr);
2251                 }
2252
2253                 public override Expression CreateExpressionTree (EmitContext ec)
2254                 {
2255                         return orig_expr.CreateExpressionTree (ec);
2256                 }
2257
2258                 public override Expression DoResolve (EmitContext ec)
2259                 {
2260                         eclass = expr.eclass;
2261                         type = expr.Type;
2262                         return this;
2263                 }
2264
2265                 public override void Emit (EmitContext ec)
2266                 {
2267                         expr.Emit (ec);
2268                 }
2269
2270                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
2271                 {
2272                         expr.EmitBranchable (ec, target, on_true);
2273                 }
2274         }
2275
2276         //
2277         // Unresolved type name expressions
2278         //
2279         public abstract class ATypeNameExpression : FullNamedExpression
2280         {
2281                 public readonly string Name;
2282                 protected TypeArguments targs;
2283
2284                 protected ATypeNameExpression (string name, Location l)
2285                 {
2286                         Name = name;
2287                         loc = l;
2288                 }
2289
2290                 protected ATypeNameExpression (string name, TypeArguments targs, Location l)
2291                 {
2292                         Name = name;
2293                         this.targs = targs;
2294                         loc = l;
2295                 }
2296
2297                 public bool HasTypeArguments {
2298                         get {
2299                                 return targs != null;
2300                         }
2301                 }
2302
2303                 public override string GetSignatureForError ()
2304                 {
2305                         if (targs != null) {
2306                                 return TypeManager.RemoveGenericArity (Name) + "<" +
2307                                         targs.GetSignatureForError () + ">";
2308                         }
2309
2310                         return Name;
2311                 }
2312         }
2313         
2314         /// <summary>
2315         ///   SimpleName expressions are formed of a single word and only happen at the beginning 
2316         ///   of a dotted-name.
2317         /// </summary>
2318         public class SimpleName : ATypeNameExpression {
2319                 bool in_transit;
2320
2321                 public SimpleName (string name, Location l)
2322                         : base (name, l)
2323                 {
2324                 }
2325
2326                 public SimpleName (string name, TypeArguments args, Location l)
2327                         : base (name, args, l)
2328                 {
2329                 }
2330
2331                 public SimpleName (string name, TypeParameter[] type_params, Location l)
2332                         : base (name, l)
2333                 {
2334                         targs = new TypeArguments (l);
2335                         foreach (TypeParameter type_param in type_params)
2336                                 targs.Add (new TypeParameterExpr (type_param, l));
2337                 }
2338
2339                 public static string RemoveGenericArity (string name)
2340                 {
2341                         int start = 0;
2342                         StringBuilder sb = null;
2343                         do {
2344                                 int pos = name.IndexOf ('`', start);
2345                                 if (pos < 0) {
2346                                         if (start == 0)
2347                                                 return name;
2348
2349                                         sb.Append (name.Substring (start));
2350                                         break;
2351                                 }
2352
2353                                 if (sb == null)
2354                                         sb = new StringBuilder ();
2355                                 sb.Append (name.Substring (start, pos-start));
2356
2357                                 pos++;
2358                                 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2359                                         pos++;
2360
2361                                 start = pos;
2362                         } while (start < name.Length);
2363
2364                         return sb.ToString ();
2365                 }
2366
2367                 public SimpleName GetMethodGroup ()
2368                 {
2369                         return new SimpleName (RemoveGenericArity (Name), targs, loc);
2370                 }
2371
2372                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2373                 {
2374                         if (ec.IsInFieldInitializer)
2375                                 Report.Error (236, l,
2376                                         "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2377                                         name);
2378                         else
2379                                 Report.Error (
2380                                         120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
2381                                         name);
2382                 }
2383
2384                 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2385                 {
2386                         return resolved_to != null && resolved_to.Type != null && 
2387                                 resolved_to.Type.Name == Name &&
2388                                 (ec.DeclContainer.LookupNamespaceOrType (Name, loc, /* ignore_cs0104 = */ true) != null);
2389                 }
2390
2391                 public override Expression DoResolve (EmitContext ec)
2392                 {
2393                         return SimpleNameResolve (ec, null, false);
2394                 }
2395
2396                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2397                 {
2398                         return SimpleNameResolve (ec, right_side, false);
2399                 }
2400                 
2401
2402                 public Expression DoResolve (EmitContext ec, bool intermediate)
2403                 {
2404                         return SimpleNameResolve (ec, null, intermediate);
2405                 }
2406
2407                 static bool IsNestedChild (Type t, Type parent)
2408                 {
2409                         while (parent != null) {
2410                                 if (TypeManager.IsNestedChildOf (t, TypeManager.DropGenericTypeArguments (parent)))
2411                                         return true;
2412
2413                                 parent = parent.BaseType;
2414                         }
2415
2416                         return false;
2417                 }
2418
2419                 FullNamedExpression ResolveNested (IResolveContext ec, Type t)
2420                 {
2421                         if (!TypeManager.IsGenericTypeDefinition (t) && !TypeManager.IsGenericType (t))
2422                                 return null;
2423
2424                         DeclSpace ds = ec.DeclContainer;
2425                         while (ds != null && !IsNestedChild (t, ds.TypeBuilder))
2426                                 ds = ds.Parent;
2427
2428                         if (ds == null)
2429                                 return null;
2430
2431                         Type[] gen_params = TypeManager.GetTypeArguments (t);
2432
2433                         int arg_count = targs != null ? targs.Count : 0;
2434
2435                         for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2436                                 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2437                                         TypeArguments new_args = new TypeArguments (loc);
2438                                         foreach (TypeParameter param in ds.TypeParameters)
2439                                                 new_args.Add (new TypeParameterExpr (param, loc));
2440
2441                                         if (targs != null)
2442                                                 new_args.Add (targs);
2443
2444                                         return new ConstructedType (t, new_args, loc);
2445                                 }
2446                         }
2447
2448                         return null;
2449                 }
2450
2451                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2452                 {
2453                         FullNamedExpression fne = ec.GenericDeclContainer.LookupGeneric (Name, loc);
2454                         if (fne != null)
2455                                 return fne.ResolveAsTypeStep (ec, silent);
2456
2457                         int errors = Report.Errors;
2458                         fne = ec.DeclContainer.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
2459
2460                         if (fne != null) {
2461                                 if (fne.Type == null)
2462                                         return fne;
2463
2464                                 FullNamedExpression nested = ResolveNested (ec, fne.Type);
2465                                 if (nested != null)
2466                                         return nested.ResolveAsTypeStep (ec, false);
2467
2468                                 if (targs != null) {
2469                                         ConstructedType ct = new ConstructedType (fne, targs, loc);
2470                                         return ct.ResolveAsTypeStep (ec, false);
2471                                 }
2472
2473                                 return fne;
2474                         }
2475
2476                         if (silent || errors != Report.Errors)
2477                                 return null;
2478
2479                         Error_TypeOrNamespaceNotFound (ec);
2480                         return null;
2481                 }
2482
2483                 protected virtual void Error_TypeOrNamespaceNotFound (IResolveContext ec)
2484                 {
2485                         MemberCore mc = ec.DeclContainer.GetDefinition (Name);
2486                         if (mc != null) {
2487                                 Error_UnexpectedKind (ec.DeclContainer, "type", GetMemberType (mc), loc);
2488                                 return;
2489                         }
2490
2491                         string ns = ec.DeclContainer.NamespaceEntry.NS.Name;
2492                         string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
2493                         foreach (Assembly a in RootNamespace.Global.Assemblies) {
2494                                 Type type = a.GetType (fullname);
2495                                 if (type != null) {
2496                                         Report.SymbolRelatedToPreviousError (type);
2497                                         Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type));
2498                                         return;
2499                                 }
2500                         }
2501
2502                         Type t = ec.DeclContainer.LookupAnyGeneric (Name);
2503                         if (t != null) {
2504                                 Namespace.Error_InvalidNumberOfTypeArguments (t, loc);
2505                                 return;
2506                         }
2507
2508                         if (targs != null) {
2509                                 FullNamedExpression retval = ec.DeclContainer.LookupNamespaceOrType (SimpleName.RemoveGenericArity (Name), loc, true);
2510                                 if (retval != null) {
2511                                         Namespace.Error_TypeArgumentsCannotBeUsed (retval.Type, loc);
2512                                         return;
2513                                 }
2514                         }
2515                                                 
2516                         NamespaceEntry.Error_NamespaceNotFound (loc, Name);
2517                 }
2518
2519                 // TODO: I am still not convinced about this. If someone else will need it
2520                 // implement this as virtual property in MemberCore hierarchy
2521                 public static string GetMemberType (MemberCore mc)
2522                 {
2523                         if (mc is Property)
2524                                 return "property";
2525                         if (mc is Indexer)
2526                                 return "indexer";
2527                         if (mc is FieldBase)
2528                                 return "field";
2529                         if (mc is MethodCore)
2530                                 return "method";
2531                         if (mc is EnumMember)
2532                                 return "enum";
2533                         if (mc is Event)
2534                                 return "event";
2535
2536                         return "type";
2537                 }
2538
2539                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2540                 {
2541                         if (in_transit)
2542                                 return null;
2543
2544                         in_transit = true;
2545                         Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2546                         in_transit = false;
2547
2548                         if (e == null)
2549                                 return null;
2550
2551                         if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2552                                 return e;
2553
2554                         return null;
2555                 }
2556
2557                 /// <remarks>
2558                 ///   7.5.2: Simple Names. 
2559                 ///
2560                 ///   Local Variables and Parameters are handled at
2561                 ///   parse time, so they never occur as SimpleNames.
2562                 ///
2563                 ///   The `intermediate' flag is used by MemberAccess only
2564                 ///   and it is used to inform us that it is ok for us to 
2565                 ///   avoid the static check, because MemberAccess might end
2566                 ///   up resolving the Name as a Type name and the access as
2567                 ///   a static type access.
2568                 ///
2569                 ///   ie: Type Type; .... { Type.GetType (""); }
2570                 ///
2571                 ///   Type is both an instance variable and a Type;  Type.GetType
2572                 ///   is the static method not an instance method of type.
2573                 /// </remarks>
2574                 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2575                 {
2576                         Expression e = null;
2577
2578                         //
2579                         // Stage 1: Performed by the parser (binding to locals or parameters).
2580                         //
2581                         Block current_block = ec.CurrentBlock;
2582                         if (current_block != null){
2583                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2584                                 if (vi != null){
2585                                         if (targs != null) {
2586                                                 Report.Error (307, loc,
2587                                                               "The variable `{0}' cannot be used with type arguments",
2588                                                               Name);
2589                                                 return null;
2590                                         }
2591
2592                                         LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2593                                         if (right_side != null) {
2594                                                 return var.ResolveLValue (ec, right_side, loc);
2595                                         } else {
2596                                                 ResolveFlags rf = ResolveFlags.VariableOrValue;
2597                                                 if (intermediate)
2598                                                         rf |= ResolveFlags.DisableFlowAnalysis;
2599                                                 return var.Resolve (ec, rf);
2600                                         }
2601                                 }
2602
2603                                 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2604                                 if (pref != null) {
2605                                         if (targs != null) {
2606                                                 Report.Error (307, loc,
2607                                                               "The variable `{0}' cannot be used with type arguments",
2608                                                               Name);
2609                                                 return null;
2610                                         }
2611
2612                                         if (right_side != null)
2613                                                 return pref.ResolveLValue (ec, right_side, loc);
2614                                         else
2615                                                 return pref.Resolve (ec);
2616                                 }
2617
2618                                 Expression expr = current_block.Toplevel.GetTransparentIdentifier (Name);
2619                                 if (expr != null) {
2620                                         if (right_side != null)
2621                                                 return expr.ResolveLValue (ec, right_side, loc);
2622                                         return expr.Resolve (ec);
2623                                 }
2624                         }
2625                         
2626                         //
2627                         // Stage 2: Lookup members 
2628                         //
2629
2630                         Type almost_matched_type = null;
2631                         ArrayList almost_matched = null;
2632                         for (DeclSpace lookup_ds = ec.DeclContainer; lookup_ds != null; lookup_ds = lookup_ds.Parent) {
2633                                 // either RootDeclSpace or GenericMethod
2634                                 if (lookup_ds.TypeBuilder == null)
2635                                         continue;
2636
2637                                 e = MemberLookup (ec.ContainerType, lookup_ds.TypeBuilder, Name, loc);
2638                                 if (e != null) {
2639                                         if (e is PropertyExpr) {
2640                                                 // since TypeManager.MemberLookup doesn't know if we're doing a lvalue access or not,
2641                                                 // it doesn't know which accessor to check permissions against
2642                                                 if (((PropertyExpr) e).IsAccessibleFrom (ec.ContainerType, right_side != null))
2643                                                         break;
2644                                         } else if (e is EventExpr) {
2645                                                 if (((EventExpr) e).IsAccessibleFrom (ec.ContainerType))
2646                                                         break;
2647                                         } else {
2648                                                 break;
2649                                         }
2650                                         e = null;
2651                                 }
2652
2653                                 if (almost_matched == null && almost_matched_members.Count > 0) {
2654                                         almost_matched_type = lookup_ds.TypeBuilder;
2655                                         almost_matched = (ArrayList) almost_matched_members.Clone ();
2656                                 }
2657                         }
2658
2659                         if (e == null) {
2660                                 if (almost_matched == null && almost_matched_members.Count > 0) {
2661                                         almost_matched_type = ec.ContainerType;
2662                                         almost_matched = (ArrayList) almost_matched_members.Clone ();
2663                                 }
2664                                 e = ResolveAsTypeStep (ec, true);
2665                         }
2666
2667                         if (e == null) {
2668                                 if (current_block != null) {
2669                                         IKnownVariable ikv = current_block.Explicit.GetKnownVariable (Name);
2670                                         if (ikv != null) {
2671                                                 LocalInfo li = ikv as LocalInfo;
2672                                                 // Supress CS0219 warning
2673                                                 if (li != null)
2674                                                         li.Used = true;
2675
2676                                                 Error_VariableIsUsedBeforeItIsDeclared (Name);
2677                                                 return null;
2678                                         }
2679                                 }
2680
2681                                 if (almost_matched != null)
2682                                         almost_matched_members = almost_matched;
2683                                 if (almost_matched_type == null)
2684                                         almost_matched_type = ec.ContainerType;
2685                                 Error_MemberLookupFailed (ec.ContainerType, null, almost_matched_type, Name,
2686                                         ec.DeclContainer.Name, AllMemberTypes, AllBindingFlags);
2687                                 return null;
2688                         }
2689
2690                         if (e is TypeExpr) {
2691                                 if (targs == null)
2692                                         return e;
2693
2694                                 ConstructedType ct = new ConstructedType (
2695                                         e.Type, targs, loc);
2696                                 return ct.ResolveAsTypeStep (ec, false);
2697                         }
2698
2699                         if (e is MemberExpr) {
2700                                 MemberExpr me = (MemberExpr) e;
2701
2702                                 Expression left;
2703                                 if (me.IsInstance) {
2704                                         if (ec.IsStatic || ec.IsInFieldInitializer) {
2705                                                 //
2706                                                 // Note that an MemberExpr can be both IsInstance and IsStatic.
2707                                                 // An unresolved MethodGroupExpr can contain both kinds of methods
2708                                                 // and each predicate is true if the MethodGroupExpr contains
2709                                                 // at least one of that kind of method.
2710                                                 //
2711
2712                                                 if (!me.IsStatic &&
2713                                                     (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2714                                                         Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2715                                                         return null;
2716                                                 }
2717
2718                                                 //
2719                                                 // Pass the buck to MemberAccess and Invocation.
2720                                                 //
2721                                                 left = EmptyExpression.Null;
2722                                         } else {
2723                                                 left = ec.GetThis (loc);
2724                                         }
2725                                 } else {
2726                                         left = new TypeExpression (ec.ContainerType, loc);
2727                                 }
2728
2729                                 me = me.ResolveMemberAccess (ec, left, loc, null);
2730                                 if (me == null)
2731                                         return null;
2732
2733                                 if (targs != null) {
2734                                         targs.Resolve (ec);
2735                                         me.SetTypeArguments (targs);
2736                                 }
2737
2738                                 if (!me.IsStatic && (me.InstanceExpression != null) &&
2739                                     TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2740                                     me.InstanceExpression.Type != me.DeclaringType &&
2741                                     !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2742                                     (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2743                                         Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2744                                                 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2745                                         return null;
2746                                 }
2747
2748                                 return (right_side != null)
2749                                         ? me.DoResolveLValue (ec, right_side)
2750                                         : me.DoResolve (ec);
2751                         }
2752
2753                         return e;
2754                 }
2755                 
2756                 protected override void CloneTo (CloneContext clonectx, Expression target)
2757                 {
2758                         // CloneTo: Nothing, we do not keep any state on this expression
2759                 }
2760         }
2761
2762         /// <summary>
2763         ///   Represents a namespace or a type.  The name of the class was inspired by
2764         ///   section 10.8.1 (Fully Qualified Names).
2765         /// </summary>
2766         public abstract class FullNamedExpression : Expression {
2767
2768                 public override Expression CreateExpressionTree (EmitContext ec)
2769                 {
2770                         throw new NotSupportedException ("ET");
2771                 }
2772
2773                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2774                 {
2775                         return this;
2776                 }
2777
2778                 public override void Emit (EmitContext ec)
2779                 {
2780                         throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
2781                                 GetSignatureForError ());
2782                 }
2783         }
2784         
2785         /// <summary>
2786         ///   Expression that evaluates to a type
2787         /// </summary>
2788         public abstract class TypeExpr : FullNamedExpression {
2789                 override public FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2790                 {
2791                         TypeExpr t = DoResolveAsTypeStep (ec);
2792                         if (t == null)
2793                                 return null;
2794
2795                         eclass = ExprClass.Type;
2796                         return t;
2797                 }
2798
2799                 override public Expression DoResolve (EmitContext ec)
2800                 {
2801                         return ResolveAsTypeTerminal (ec, false);
2802                 }
2803
2804                 public virtual bool CheckAccessLevel (DeclSpace ds)
2805                 {
2806                         return ds.CheckAccessLevel (Type);
2807                 }
2808
2809                 public virtual bool AsAccessible (DeclSpace ds)
2810                 {
2811                         return ds.IsAccessibleAs (Type);
2812                 }
2813
2814                 public virtual bool IsClass {
2815                         get { return Type.IsClass; }
2816                 }
2817
2818                 public virtual bool IsValueType {
2819                         get { return Type.IsValueType; }
2820                 }
2821
2822                 public virtual bool IsInterface {
2823                         get { return Type.IsInterface; }
2824                 }
2825
2826                 public virtual bool IsSealed {
2827                         get { return Type.IsSealed; }
2828                 }
2829
2830                 public virtual bool CanInheritFrom ()
2831                 {
2832                         if (Type == TypeManager.enum_type ||
2833                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2834                             Type == TypeManager.multicast_delegate_type ||
2835                             Type == TypeManager.delegate_type ||
2836                             Type == TypeManager.array_type)
2837                                 return false;
2838
2839                         return true;
2840                 }
2841
2842                 protected abstract TypeExpr DoResolveAsTypeStep (IResolveContext ec);
2843
2844                 public override bool Equals (object obj)
2845                 {
2846                         TypeExpr tobj = obj as TypeExpr;
2847                         if (tobj == null)
2848                                 return false;
2849
2850                         return Type == tobj.Type;
2851                 }
2852
2853                 public override int GetHashCode ()
2854                 {
2855                         return Type.GetHashCode ();
2856                 }
2857
2858                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2859                 {
2860                         type = storey.MutateType (type);
2861                 }
2862         }
2863
2864         /// <summary>
2865         ///   Fully resolved Expression that already evaluated to a type
2866         /// </summary>
2867         public class TypeExpression : TypeExpr {
2868                 public TypeExpression (Type t, Location l)
2869                 {
2870                         Type = t;
2871                         eclass = ExprClass.Type;
2872                         loc = l;
2873                 }
2874
2875                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2876                 {
2877                         return this;
2878                 }
2879
2880                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2881                 {
2882                         return this;
2883                 }
2884         }
2885
2886         /// <summary>
2887         ///   Used to create types from a fully qualified name.  These are just used
2888         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2889         ///   classified as a type.
2890         /// </summary>
2891         public sealed class TypeLookupExpression : TypeExpr {
2892                 readonly string name;
2893                 
2894                 public TypeLookupExpression (string name)
2895                 {
2896                         this.name = name;
2897                         eclass = ExprClass.Type;
2898                 }
2899
2900                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2901                 {
2902                         // It's null for corlib compilation only
2903                         if (type == null)
2904                                 return DoResolveAsTypeStep (ec);
2905
2906                         return this;
2907                 }
2908
2909                 private class UnexpectedType
2910                 {
2911                 }
2912
2913                 // This performes recursive type lookup, providing support for generic types.
2914                 // For example, given the type:
2915                 //
2916                 // System.Collections.Generic.KeyValuePair`2[[System.Int32],[System.String]]
2917                 //
2918                 // The types will be checked in the following order:
2919                 //                                                                             _
2920                 // System                                                                       |
2921                 // System.Collections                                                           |
2922                 // System.Collections.Generic                                                   |
2923                 //                        _                                                     |
2924                 //     System              | recursive call 1                                   |
2925                 //     System.Int32       _|                                                    | main method call
2926                 //                        _                                                     |
2927                 //     System              | recursive call 2                                   |
2928                 //     System.String      _|                                                    |
2929                 //                                                                              |
2930                 // System.Collections.Generic.KeyValuePair`2[[System.Int32],[System.String]]   _|
2931                 //
2932                 private Type TypeLookup (IResolveContext ec, string name)
2933                 {
2934                         int index = 0;
2935                         int dot = 0;
2936                         bool done = false;
2937                         FullNamedExpression resolved = null;
2938                         Type type = null;
2939                         Type recursive_type = null;
2940                         while (index < name.Length) {
2941                                 if (name[index] == '[') {
2942                                         int open = index;
2943                                         int braces = 1;
2944                                         do {
2945                                                 index++;
2946                                                 if (name[index] == '[')
2947                                                         braces++;
2948                                                 else if (name[index] == ']')
2949                                                         braces--;
2950                                         } while (braces > 0);
2951                                         recursive_type = TypeLookup (ec, name.Substring (open + 1, index - open - 1));
2952                                         if (recursive_type == null || (recursive_type == typeof(UnexpectedType)))
2953                                                 return recursive_type;
2954                                 }
2955                                 else {
2956                                         if (name[index] == ',')
2957                                                 done = true;
2958                                         else if ((name[index] == '.' && !done) || (index == name.Length && name[0] != '[')) {
2959                                                 string substring = name.Substring(dot, index - dot);
2960
2961                                                 if (resolved == null)
2962                                                         resolved = RootNamespace.Global.Lookup (ec.DeclContainer, substring, Location.Null);
2963                                                 else if (resolved is Namespace)
2964                                                     resolved = (resolved as Namespace).Lookup (ec.DeclContainer, substring, Location.Null);
2965                                                 else if (type != null)
2966                                                         type = TypeManager.GetNestedType (type, substring);
2967                                                 else
2968                                                         return null;
2969
2970                                                 if (resolved == null)
2971                                                         return null;
2972                                                 else if (type == null && resolved is TypeExpr)
2973                                                         type = resolved.Type;
2974
2975                                                 dot = index + 1;
2976                                         }
2977                                 }
2978                                 index++;
2979                         }
2980                         if (name[0] != '[') {
2981                                 string substring = name.Substring(dot, index - dot);
2982
2983                                 if (type != null)
2984                                         return TypeManager.GetNestedType (type, substring);
2985                                 
2986                                 if (resolved != null) {
2987                                         resolved = (resolved as Namespace).Lookup (ec.DeclContainer, substring, Location.Null);
2988                                         if (resolved is TypeExpr)
2989                                                 return resolved.Type;
2990                                         
2991                                         if (resolved == null)
2992                                                 return null;
2993                                         
2994                                         resolved.Error_UnexpectedKind (ec.DeclContainer, "type", loc);
2995                                         return typeof (UnexpectedType);
2996                                 }
2997                                 else
2998                                         return null;
2999                         }
3000                         else
3001                                 return recursive_type;
3002                         }
3003
3004                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
3005                 {
3006                         Type t = TypeLookup (ec, name);
3007                         if (t == null) {
3008                                 NamespaceEntry.Error_NamespaceNotFound (loc, name);
3009                                 return null;
3010                         }
3011                         if (t == typeof(UnexpectedType))
3012                                 return null;
3013                         type = t;
3014                         return this;
3015                 }
3016
3017                 protected override void CloneTo (CloneContext clonectx, Expression target)
3018                 {
3019                         // CloneTo: Nothing, we do not keep any state on this expression
3020                 }
3021
3022                 public override string GetSignatureForError ()
3023                 {
3024                         if (type == null)
3025                                 return TypeManager.CSharpName (name);
3026
3027                         return base.GetSignatureForError ();
3028                 }
3029         }
3030
3031         /// <summary>
3032         ///   Represents an "unbound generic type", ie. typeof (Foo<>).
3033         ///   See 14.5.11.
3034         /// </summary>
3035         public class UnboundTypeExpression : TypeExpr
3036         {
3037                 MemberName name;
3038
3039                 public UnboundTypeExpression (MemberName name, Location l)
3040                 {
3041                         this.name = name;
3042                         loc = l;
3043                 }
3044
3045                 protected override void CloneTo (CloneContext clonectx, Expression target)
3046                 {
3047                         // Nothing to clone
3048                 }
3049
3050                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
3051                 {
3052                         Expression expr;
3053                         if (name.Left != null) {
3054                                 Expression lexpr = name.Left.GetTypeExpression ();
3055                                 expr = new MemberAccess (lexpr, name.Basename);
3056                         } else {
3057                                 expr = new SimpleName (name.Basename, loc);
3058                         }
3059
3060                         FullNamedExpression fne = expr.ResolveAsTypeStep (ec, false);
3061                         if (fne == null)
3062                                 return null;
3063
3064                         type = fne.Type;
3065                         return new TypeExpression (type, loc);
3066                 }
3067         }
3068
3069         /// <summary>
3070         ///   This class denotes an expression which evaluates to a member
3071         ///   of a struct or a class.
3072         /// </summary>
3073         public abstract class MemberExpr : Expression
3074         {
3075                 protected bool is_base;
3076
3077                 /// <summary>
3078                 ///   The name of this member.
3079                 /// </summary>
3080                 public abstract string Name {
3081                         get;
3082                 }
3083
3084                 //
3085                 // When base.member is used
3086                 //
3087                 public bool IsBase {
3088                         get { return is_base; }
3089                         set { is_base = value; }
3090                 }
3091
3092                 /// <summary>
3093                 ///   Whether this is an instance member.
3094                 /// </summary>
3095                 public abstract bool IsInstance {
3096                         get;
3097                 }
3098
3099                 /// <summary>
3100                 ///   Whether this is a static member.
3101                 /// </summary>
3102                 public abstract bool IsStatic {
3103                         get;
3104                 }
3105
3106                 /// <summary>
3107                 ///   The type which declares this member.
3108                 /// </summary>
3109                 public abstract Type DeclaringType {
3110                         get;
3111                 }
3112
3113                 /// <summary>
3114                 ///   The instance expression associated with this member, if it's a
3115                 ///   non-static member.
3116                 /// </summary>
3117                 public Expression InstanceExpression;
3118
3119                 public static void error176 (Location loc, string name)
3120                 {
3121                         Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
3122                                       "with an instance reference, qualify it with a type name instead", name);
3123                 }
3124
3125                 public static void Error_BaseAccessInExpressionTree (Location loc)
3126                 {
3127                         Report.Error (831, loc, "An expression tree may not contain a base access");
3128                 }
3129
3130                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3131                 {
3132                         if (InstanceExpression != null)
3133                                 InstanceExpression.MutateHoistedGenericType (storey);
3134                 }
3135
3136                 // TODO: possible optimalization
3137                 // Cache resolved constant result in FieldBuilder <-> expression map
3138                 public virtual MemberExpr ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3139                                                                SimpleName original)
3140                 {
3141                         //
3142                         // Precondition:
3143                         //   original == null || original.Resolve (...) ==> left
3144                         //
3145
3146                         if (left is TypeExpr) {
3147                                 left = left.ResolveAsTypeTerminal (ec, true);
3148                                 if (left == null)
3149                                         return null;
3150
3151                                 if (!IsStatic) {
3152                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3153                                         return null;
3154                                 }
3155
3156                                 return this;
3157                         }
3158                                 
3159                         if (!IsInstance) {
3160                                 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3161                                         return this;
3162
3163                                 return ResolveExtensionMemberAccess (left);
3164                         }
3165
3166                         InstanceExpression = left;
3167                         return this;
3168                 }
3169
3170                 protected virtual MemberExpr ResolveExtensionMemberAccess (Expression left)
3171                 {
3172                         error176 (loc, GetSignatureForError ());
3173                         return this;
3174                 }
3175
3176                 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
3177                 {
3178                         if (IsStatic)
3179                                 return;
3180
3181                         if (InstanceExpression == EmptyExpression.Null) {
3182                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3183                                 return;
3184                         }
3185                                 
3186                         if (InstanceExpression.Type.IsValueType) {
3187                                 if (InstanceExpression is IMemoryLocation) {
3188                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3189                                 } else {
3190                                         LocalTemporary t = new LocalTemporary (InstanceExpression.Type);
3191                                         InstanceExpression.Emit (ec);
3192                                         t.Store (ec);
3193                                         t.AddressOf (ec, AddressOp.Store);
3194                                 }
3195                         } else
3196                                 InstanceExpression.Emit (ec);
3197
3198                         if (prepare_for_load)
3199                                 ec.ig.Emit (OpCodes.Dup);
3200                 }
3201
3202                 public virtual void SetTypeArguments (TypeArguments ta)
3203                 {
3204                         // TODO: need to get correct member type
3205                         Report.Error (307, loc, "The property `{0}' cannot be used with type arguments",
3206                                 GetSignatureForError ());
3207                 }
3208         }
3209
3210         /// 
3211         /// Represents group of extension methods
3212         /// 
3213         public class ExtensionMethodGroupExpr : MethodGroupExpr
3214         {
3215                 readonly NamespaceEntry namespace_entry;
3216                 public Expression ExtensionExpression;
3217                 Argument extension_argument;
3218
3219                 public ExtensionMethodGroupExpr (ArrayList list, NamespaceEntry n, Type extensionType, Location l)
3220                         : base (list, extensionType, l)
3221                 {
3222                         this.namespace_entry = n;
3223                 }
3224
3225                 public override bool IsStatic {
3226                         get { return true; }
3227                 }
3228
3229                 public bool IsTopLevel {
3230                         get { return namespace_entry == null; }
3231                 }
3232
3233                 public override void EmitArguments (EmitContext ec, ArrayList arguments)
3234                 {
3235                         if (arguments == null)
3236                                 arguments = new ArrayList (1);                  
3237                         arguments.Insert (0, extension_argument);
3238                         base.EmitArguments (ec, arguments);
3239                 }
3240
3241                 public override void EmitCall (EmitContext ec, ArrayList arguments)
3242                 {
3243                         if (arguments == null)
3244                                 arguments = new ArrayList (1);
3245                         arguments.Insert (0, extension_argument);
3246                         base.EmitCall (ec, arguments);
3247                 }
3248
3249                 public override MethodGroupExpr OverloadResolve (EmitContext ec, ref ArrayList arguments, bool may_fail, Location loc)
3250                 {
3251                         if (arguments == null)
3252                                 arguments = new ArrayList (1);
3253
3254                         arguments.Insert (0, new Argument (ExtensionExpression));
3255                         MethodGroupExpr mg = ResolveOverloadExtensions (ec, arguments, namespace_entry, loc);
3256
3257                         // Store resolved argument and restore original arguments
3258                         if (mg != null)
3259                                 ((ExtensionMethodGroupExpr)mg).extension_argument = (Argument)arguments [0];
3260                         arguments.RemoveAt (0);
3261
3262                         return mg;
3263                 }
3264
3265                 MethodGroupExpr ResolveOverloadExtensions (EmitContext ec, ArrayList arguments, NamespaceEntry ns, Location loc)
3266                 {
3267                         // Use normal resolve rules
3268                         MethodGroupExpr mg = base.OverloadResolve (ec, ref arguments, ns != null, loc);
3269                         if (mg != null)
3270                                 return mg;
3271
3272                         if (ns == null)
3273                                 return null;
3274
3275                         // Search continues
3276                         ExtensionMethodGroupExpr e = ns.LookupExtensionMethod (type, null, Name, loc);
3277                         if (e == null)
3278                                 return base.OverloadResolve (ec, ref arguments, false, loc);
3279
3280                         e.ExtensionExpression = ExtensionExpression;
3281                         e.SetTypeArguments (type_arguments);                    
3282                         return e.ResolveOverloadExtensions (ec, arguments, e.namespace_entry, loc);
3283                 }               
3284         }
3285
3286         /// <summary>
3287         ///   MethodGroupExpr represents a group of method candidates which
3288         ///   can be resolved to the best method overload
3289         /// </summary>
3290         public class MethodGroupExpr : MemberExpr
3291         {
3292                 public interface IErrorHandler
3293                 {
3294                         bool NoExactMatch (EmitContext ec, MethodBase method);
3295                 }
3296
3297                 public IErrorHandler CustomErrorHandler;                
3298                 public MethodBase [] Methods;
3299                 MethodBase best_candidate;
3300                 // TODO: make private
3301                 public TypeArguments type_arguments;
3302                 bool identical_type_name;
3303                 Type delegate_type;
3304                 
3305                 public MethodGroupExpr (MemberInfo [] mi, Type type, Location l)
3306                         : this (type, l)
3307                 {
3308                         Methods = new MethodBase [mi.Length];
3309                         mi.CopyTo (Methods, 0);
3310                 }
3311
3312                 public MethodGroupExpr (ArrayList list, Type type, Location l)
3313                         : this (type, l)
3314                 {
3315                         try {
3316                                 Methods = (MethodBase[])list.ToArray (typeof (MethodBase));
3317                         } catch {
3318                                 foreach (MemberInfo m in list){
3319                                         if (!(m is MethodBase)){
3320                                                 Console.WriteLine ("Name " + m.Name);
3321                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3322                                         }
3323                                 }
3324                                 throw;
3325                         }
3326
3327
3328                 }
3329
3330                 protected MethodGroupExpr (Type type, Location loc)
3331                 {
3332                         this.loc = loc;
3333                         eclass = ExprClass.MethodGroup;
3334                         this.type = type;
3335                 }
3336
3337                 public override Type DeclaringType {
3338                         get {
3339                                 //
3340                                 // We assume that the top-level type is in the end
3341                                 //
3342                                 return Methods [Methods.Length - 1].DeclaringType;
3343                                 //return Methods [0].DeclaringType;
3344                         }
3345                 }
3346
3347                 public Type DelegateType {
3348                         set {
3349                                 delegate_type = value;
3350                         }
3351                 }
3352
3353                 public bool IdenticalTypeName {
3354                         get {
3355                                 return identical_type_name;
3356                         }
3357
3358                         set {
3359                                 identical_type_name = value;
3360                         }
3361                 }
3362
3363                 public override string GetSignatureForError ()
3364                 {
3365                         if (best_candidate != null)
3366                                 return TypeManager.CSharpSignature (best_candidate);
3367                         
3368                         return TypeManager.CSharpSignature (Methods [0]);
3369                 }
3370
3371                 public override string Name {
3372                         get {
3373                                 return Methods [0].Name;
3374                         }
3375                 }
3376
3377                 public override bool IsInstance {
3378                         get {
3379                                 if (best_candidate != null)
3380                                         return !best_candidate.IsStatic;
3381
3382                                 foreach (MethodBase mb in Methods)
3383                                         if (!mb.IsStatic)
3384                                                 return true;
3385
3386                                 return false;
3387                         }
3388                 }
3389
3390                 public override bool IsStatic {
3391                         get {
3392                                 if (best_candidate != null)
3393                                         return best_candidate.IsStatic;
3394
3395                                 foreach (MethodBase mb in Methods)
3396                                         if (mb.IsStatic)
3397                                                 return true;
3398
3399                                 return false;
3400                         }
3401                 }
3402                 
3403                 public static explicit operator ConstructorInfo (MethodGroupExpr mg)
3404                 {
3405                         return (ConstructorInfo)mg.best_candidate;
3406                 }
3407
3408                 public static explicit operator MethodInfo (MethodGroupExpr mg)
3409                 {
3410                         return (MethodInfo)mg.best_candidate;
3411                 }
3412
3413                 //
3414                 //  7.4.3.3  Better conversion from expression
3415                 //  Returns :   1    if a->p is better,
3416                 //              2    if a->q is better,
3417                 //              0 if neither is better
3418                 //
3419                 static int BetterExpressionConversion (EmitContext ec, Argument a, Type p, Type q)
3420                 {
3421                         Type argument_type = TypeManager.TypeToCoreType (a.Type);
3422                         if (argument_type == TypeManager.anonymous_method_type && RootContext.Version > LanguageVersion.ISO_2) {
3423                                 //
3424                                 // Uwrap delegate from Expression<T>
3425                                 //
3426                                 if (TypeManager.DropGenericTypeArguments (p) == TypeManager.expression_type) {
3427                                         p = TypeManager.GetTypeArguments (p) [0];
3428                                 }
3429                                 if (TypeManager.DropGenericTypeArguments (q) == TypeManager.expression_type) {
3430                                         q = TypeManager.GetTypeArguments (q) [0];
3431                                 }
3432                                 
3433                                 p = Delegate.GetInvokeMethod (null, p).ReturnType;
3434                                 q = Delegate.GetInvokeMethod (null, q).ReturnType;
3435                                 if (p == TypeManager.void_type && q != TypeManager.void_type)
3436                                         return 2;
3437                                 if (q == TypeManager.void_type && p != TypeManager.void_type)
3438                                         return 1;
3439                         } else {
3440                                 if (argument_type == p)
3441                                         return 1;
3442
3443                                 if (argument_type == q)
3444                                         return 2;
3445                         }
3446
3447                         return BetterTypeConversion (ec, p, q);
3448                 }
3449
3450                 //
3451                 // 7.4.3.4  Better conversion from type
3452                 //
3453                 public static int BetterTypeConversion (EmitContext ec, Type p, Type q)
3454                 {
3455                         if (p == null || q == null)
3456                                 throw new InternalErrorException ("BetterTypeConversion got a null conversion");
3457
3458                         if (p == TypeManager.int32_type) {
3459                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3460                                         return 1;
3461                         } else if (p == TypeManager.int64_type) {
3462                                 if (q == TypeManager.uint64_type)
3463                                         return 1;
3464                         } else if (p == TypeManager.sbyte_type) {
3465                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3466                                         q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3467                                         return 1;
3468                         } else if (p == TypeManager.short_type) {
3469                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3470                                         q == TypeManager.uint64_type)
3471                                         return 1;
3472                         }
3473
3474                         if (q == TypeManager.int32_type) {
3475                                 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3476                                         return 2;
3477                         } if (q == TypeManager.int64_type) {
3478                                 if (p == TypeManager.uint64_type)
3479                                         return 2;
3480                         } else if (q == TypeManager.sbyte_type) {
3481                                 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
3482                                         p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3483                                         return 2;
3484                         } if (q == TypeManager.short_type) {
3485                                 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
3486                                         p == TypeManager.uint64_type)
3487                                         return 2;
3488                         }
3489
3490                         // TODO: this is expensive
3491                         Expression p_tmp = new EmptyExpression (p);
3492                         Expression q_tmp = new EmptyExpression (q);
3493
3494                         bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
3495                         bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
3496
3497                         if (p_to_q && !q_to_p)
3498                                 return 1;
3499
3500                         if (q_to_p && !p_to_q)
3501                                 return 2;
3502
3503                         return 0;
3504                 }
3505
3506                 /// <summary>
3507                 ///   Determines "Better function" between candidate
3508                 ///   and the current best match
3509                 /// </summary>
3510                 /// <remarks>
3511                 ///    Returns a boolean indicating :
3512                 ///     false if candidate ain't better
3513                 ///     true  if candidate is better than the current best match
3514                 /// </remarks>
3515                 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
3516                         MethodBase candidate, bool candidate_params,
3517                         MethodBase best, bool best_params)
3518                 {
3519                         ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
3520                         ParameterData best_pd = TypeManager.GetParameterData (best);
3521                 
3522                         bool better_at_least_one = false;
3523                         bool same = true;
3524                         for (int j = 0, c_idx = 0, b_idx = 0; j < argument_count; ++j, ++c_idx, ++b_idx) 
3525                         {
3526                                 Argument a = (Argument) args [j];
3527
3528                                 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (c_idx));
3529                                 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (b_idx));
3530
3531                                 if (candidate_params && candidate_pd.ParameterModifier (c_idx) == Parameter.Modifier.PARAMS) 
3532                                 {
3533                                         ct = TypeManager.GetElementType (ct);
3534                                         --c_idx;
3535                                 }
3536
3537                                 if (best_params && best_pd.ParameterModifier (b_idx) == Parameter.Modifier.PARAMS) 
3538                                 {
3539                                         bt = TypeManager.GetElementType (bt);
3540                                         --b_idx;
3541                                 }
3542
3543                                 if (ct.Equals (bt))
3544                                         continue;
3545
3546                                 same = false;
3547                                 int result = BetterExpressionConversion (ec, a, ct, bt);
3548
3549                                 // for each argument, the conversion to 'ct' should be no worse than 
3550                                 // the conversion to 'bt'.
3551                                 if (result == 2)
3552                                         return false;
3553
3554                                 // for at least one argument, the conversion to 'ct' should be better than 
3555                                 // the conversion to 'bt'.
3556                                 if (result != 0)
3557                                         better_at_least_one = true;
3558                         }
3559
3560                         if (better_at_least_one)
3561                                 return true;
3562
3563                         //
3564                         // This handles the case
3565                         //
3566                         //   Add (float f1, float f2, float f3);
3567                         //   Add (params decimal [] foo);
3568                         //
3569                         // The call Add (3, 4, 5) should be ambiguous.  Without this check, the
3570                         // first candidate would've chosen as better.
3571                         //
3572                         if (!same)
3573                                 return false;
3574
3575                         //
3576                         // The two methods have equal parameter types.  Now apply tie-breaking rules
3577                         //
3578                         if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
3579                                 return true;
3580                         if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
3581                                 return false;
3582
3583                         //
3584                         // This handles the following cases:
3585                         //
3586                         //   Trim () is better than Trim (params char[] chars)
3587                         //   Concat (string s1, string s2, string s3) is better than
3588                         //     Concat (string s1, params string [] srest)
3589                         //   Foo (int, params int [] rest) is better than Foo (params int [] rest)
3590                         //
3591                         if (!candidate_params && best_params)
3592                                 return true;
3593                         if (candidate_params && !best_params)
3594                                 return false;
3595
3596                         int candidate_param_count = candidate_pd.Count;
3597                         int best_param_count = best_pd.Count;
3598
3599                         if (candidate_param_count != best_param_count)
3600                                 // can only happen if (candidate_params && best_params)
3601                                 return candidate_param_count > best_param_count;
3602
3603                         //
3604                         // now, both methods have the same number of parameters, and the parameters have the same types
3605                         // Pick the "more specific" signature
3606                         //
3607
3608                         MethodBase orig_candidate = TypeManager.DropGenericMethodArguments (candidate);
3609                         MethodBase orig_best = TypeManager.DropGenericMethodArguments (best);
3610
3611                         ParameterData orig_candidate_pd = TypeManager.GetParameterData (orig_candidate);
3612                         ParameterData orig_best_pd = TypeManager.GetParameterData (orig_best);
3613
3614                         bool specific_at_least_once = false;
3615                         for (int j = 0; j < candidate_param_count; ++j) 
3616                         {
3617                                 Type ct = TypeManager.TypeToCoreType (orig_candidate_pd.ParameterType (j));
3618                                 Type bt = TypeManager.TypeToCoreType (orig_best_pd.ParameterType (j));
3619                                 if (ct.Equals (bt))
3620                                         continue;
3621                                 Type specific = MoreSpecific (ct, bt);
3622                                 if (specific == bt)
3623                                         return false;
3624                                 if (specific == ct)
3625                                         specific_at_least_once = true;
3626                         }
3627
3628                         if (specific_at_least_once)
3629                                 return true;
3630
3631                         // FIXME: handle lifted operators
3632                         // ...
3633
3634                         return false;
3635                 }
3636
3637                 protected override MemberExpr ResolveExtensionMemberAccess (Expression left)
3638                 {
3639                         if (!IsStatic)
3640                                 return base.ResolveExtensionMemberAccess (left);
3641
3642                         //
3643                         // When left side is an expression and at least one candidate method is 
3644                         // static, it can be extension method
3645                         //
3646                         InstanceExpression = left;
3647                         return this;
3648                 }
3649
3650                 public override MemberExpr ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3651                                                                 SimpleName original)
3652                 {
3653                         if (!(left is TypeExpr) &&
3654                             original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3655                                 IdenticalTypeName = true;
3656
3657                         return base.ResolveMemberAccess (ec, left, loc, original);
3658                 }
3659
3660                 public override Expression CreateExpressionTree (EmitContext ec)
3661                 {
3662                         if (best_candidate == null) {
3663                                 Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
3664                                 return null;
3665                         }
3666
3667                         if (best_candidate.IsConstructor)
3668                                 return new TypeOfConstructorInfo (best_candidate, loc);
3669
3670                         IMethodData md = TypeManager.GetMethod (best_candidate);
3671                         if (md != null && md.IsExcluded ())
3672                                 Report.Error (765, loc,
3673                                         "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
3674                         
3675                         return new TypeOfMethodInfo (best_candidate, loc);
3676                 }
3677                 
3678                 override public Expression DoResolve (EmitContext ec)
3679                 {
3680                         if (InstanceExpression != null) {
3681                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3682                                 if (InstanceExpression == null)
3683                                         return null;
3684                         }
3685
3686                         return this;
3687                 }
3688
3689                 public void ReportUsageError ()
3690                 {
3691                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
3692                                       Name + "()' is referenced without parentheses");
3693                 }
3694
3695                 override public void Emit (EmitContext ec)
3696                 {
3697                         ReportUsageError ();
3698                 }
3699                 
3700                 public virtual void EmitArguments (EmitContext ec, ArrayList arguments)
3701                 {
3702                         Invocation.EmitArguments (ec, arguments, false, null);  
3703                 }
3704                 
3705                 public virtual void EmitCall (EmitContext ec, ArrayList arguments)
3706                 {
3707                         Invocation.EmitCall (ec, IsBase, InstanceExpression, best_candidate, arguments, loc);                   
3708                 }
3709
3710                 protected virtual void Error_InvalidArguments (EmitContext ec, Location loc, int idx, MethodBase method,
3711                                                                                                         Argument a, ParameterData expected_par, Type paramType)
3712                 {
3713                         ExtensionMethodGroupExpr emg = this as ExtensionMethodGroupExpr;
3714
3715                         if (a is CollectionElementInitializer.ElementInitializerArgument) {
3716                                 Report.SymbolRelatedToPreviousError (method);
3717                                 if ((expected_par.ParameterModifier (idx) & Parameter.Modifier.ISBYREF) != 0) {
3718                                         Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
3719                                                 TypeManager.CSharpSignature (method));
3720                                         return;
3721                                 }
3722                                 Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
3723                                           TypeManager.CSharpSignature (method));
3724                         } else if (delegate_type == null) {
3725                                 Report.SymbolRelatedToPreviousError (method);
3726                                 if (emg != null) {
3727                                         Report.Error (1928, loc,
3728                                                 "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
3729                                                 emg.ExtensionExpression.GetSignatureForError (),
3730                                                 emg.Name, TypeManager.CSharpSignature (method));
3731                                 } else {
3732                                         Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
3733                                                 TypeManager.CSharpSignature (method));
3734                                 }
3735                         } else
3736                                 Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
3737                                         TypeManager.CSharpName (delegate_type));
3738
3739                         Parameter.Modifier mod = expected_par.ParameterModifier (idx);
3740
3741                         string index = (idx + 1).ToString ();
3742                         if (((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) ^
3743                                 (a.Modifier & (Parameter.Modifier.REF | Parameter.Modifier.OUT))) != 0) {
3744                                 if ((mod & Parameter.Modifier.ISBYREF) == 0)
3745                                         Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
3746                                                 index, Parameter.GetModifierSignature (a.Modifier));
3747                                 else
3748                                         Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
3749                                                 index, Parameter.GetModifierSignature (mod));
3750                         } else {
3751                                 string p1 = a.GetSignatureForError ();
3752                                 string p2 = TypeManager.CSharpName (paramType);
3753
3754                                 if (p1 == p2) {
3755                                         Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
3756                                         Report.SymbolRelatedToPreviousError (a.Expr.Type);
3757                                         Report.SymbolRelatedToPreviousError (paramType);
3758                                 }
3759
3760                                 if (idx == 0 && emg != null) {
3761                                         Report.Error (1929, loc,
3762                                                 "Extension method instance type `{0}' cannot be converted to `{1}'", p1, p2);
3763                                 } else {
3764                                         Report.Error (1503, loc,
3765                                                 "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
3766                                 }
3767                         }
3768                 }
3769
3770                 public override void Error_ValueCannotBeConverted (EmitContext ec, Location loc, Type target, bool expl)
3771                 {
3772                         Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
3773                                 Name, TypeManager.CSharpName (target));
3774                 }
3775                 
3776                 protected virtual int GetApplicableParametersCount (MethodBase method, ParameterData parameters)
3777                 {
3778                         return parameters.Count;
3779                 }               
3780
3781                 public static bool IsAncestralType (Type first_type, Type second_type)
3782                 {
3783                         return first_type != second_type &&
3784                                 (TypeManager.IsSubclassOf (second_type, first_type) ||
3785                                 TypeManager.ImplementsInterface (second_type, first_type));
3786                 }
3787
3788                 ///
3789                 /// Determines if the candidate method is applicable (section 14.4.2.1)
3790                 /// to the given set of arguments
3791                 /// A return value rates candidate method compatibility,
3792                 /// 0 = the best, int.MaxValue = the worst
3793                 ///
3794                 public int IsApplicable (EmitContext ec,
3795                                                  ArrayList arguments, int arg_count, ref MethodBase method, ref bool params_expanded_form)
3796                 {
3797                         MethodBase candidate = method;
3798
3799                         ParameterData pd = TypeManager.GetParameterData (candidate);
3800                         int param_count = GetApplicableParametersCount (candidate, pd);
3801
3802                         if (arg_count != param_count) {
3803                                 if (!pd.HasParams)
3804                                         return int.MaxValue - 10000 + Math.Abs (arg_count - param_count);
3805                                 if (arg_count < param_count - 1)
3806                                         return int.MaxValue - 10000 + Math.Abs (arg_count - param_count);
3807                         }
3808
3809 #if GMCS_SOURCE
3810                         //
3811                         // 1. Handle generic method using type arguments when specified or type inference
3812                         //
3813                         if (TypeManager.IsGenericMethod (candidate)) {
3814                                 if (type_arguments != null) {
3815                                         Type [] g_args = candidate.GetGenericArguments ();
3816                                         if (g_args.Length != type_arguments.Count)
3817                                                 return int.MaxValue - 20000 + Math.Abs (type_arguments.Count - g_args.Length);
3818
3819                                         // TODO: Don't create new method, create Parameters only
3820                                         method = ((MethodInfo) candidate).MakeGenericMethod (type_arguments.Arguments);
3821                                         candidate = method;
3822                                         pd = TypeManager.GetParameterData (candidate);
3823                                 } else {
3824                                         int score = TypeManager.InferTypeArguments (ec, arguments, ref candidate);
3825                                         if (score != 0)
3826                                                 return score - 20000;
3827
3828                                         if (TypeManager.IsGenericMethodDefinition (candidate))
3829                                                 throw new InternalErrorException ("A generic method `{0}' definition took part in overload resolution",
3830                                                         TypeManager.CSharpSignature (candidate));
3831
3832                                         pd = TypeManager.GetParameterData (candidate);
3833                                 }
3834                         } else {
3835                                 if (type_arguments != null)
3836                                         return int.MaxValue - 15000;
3837                         }
3838 #endif                  
3839
3840                         //
3841                         // 2. Each argument has to be implicitly convertible to method parameter
3842                         //
3843                         method = candidate;
3844                         Parameter.Modifier p_mod = 0;
3845                         Type pt = null;
3846                         for (int i = 0; i < arg_count; i++) {
3847                                 Argument a = (Argument) arguments [i];
3848                                 Parameter.Modifier a_mod = a.Modifier &
3849                                         ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
3850
3851                                 if (p_mod != Parameter.Modifier.PARAMS) {
3852                                         p_mod = pd.ParameterModifier (i) & ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
3853
3854                                         if (p_mod == Parameter.Modifier.ARGLIST) {
3855                                                 if (a.Type == TypeManager.runtime_argument_handle_type)
3856                                                         continue;
3857
3858                                                 p_mod = 0;
3859                                         }
3860
3861                                         pt = pd.ParameterType (i);
3862                                 } else {
3863                                         params_expanded_form = true;
3864                                 }
3865
3866                                 int score = 1;
3867                                 if (!params_expanded_form)
3868                                         score = IsArgumentCompatible (ec, a_mod, a, p_mod & ~Parameter.Modifier.PARAMS, pt);
3869
3870                                 if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0) {
3871                                         // It can be applicable in expanded form
3872                                         score = IsArgumentCompatible (ec, a_mod, a, 0, pt.GetElementType ());
3873                                         if (score == 0)
3874                                                 params_expanded_form = true;
3875                                 }
3876
3877                                 if (score != 0) {
3878                                         if (params_expanded_form)
3879                                                 ++score;
3880                                         return (arg_count - i) * 2 + score;
3881                                 }
3882                         }
3883                         
3884                         if (arg_count != param_count)
3885                                 params_expanded_form = true;                    
3886                         
3887                         return 0;
3888                 }
3889
3890                 int IsArgumentCompatible (EmitContext ec, Parameter.Modifier arg_mod, Argument argument, Parameter.Modifier param_mod, Type parameter)
3891                 {
3892                         //
3893                         // Types have to be identical when ref or out modifer is used 
3894                         //
3895                         if (arg_mod != 0 || param_mod != 0) {
3896                                 if (TypeManager.HasElementType (parameter))
3897                                         parameter = parameter.GetElementType ();
3898
3899                                 Type a_type = argument.Type;
3900                                 if (TypeManager.HasElementType (a_type))
3901                                         a_type = a_type.GetElementType ();
3902
3903                                 if (a_type != parameter)
3904                                         return 2;
3905                         } else {
3906                                 if (delegate_type != null ?
3907                                         !Delegate.IsTypeCovariant (argument.Expr, parameter) :
3908                                         !Convert.ImplicitConversionExists (ec, argument.Expr, parameter))
3909                                         return 2;
3910                         }
3911
3912                         if (arg_mod != param_mod)
3913                                 return 1;
3914
3915                         return 0;
3916                 }
3917
3918                 public static bool IsOverride (MethodBase cand_method, MethodBase base_method)
3919                 {
3920                         if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
3921                                 return false;
3922
3923                         ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
3924                         ParameterData base_pd = TypeManager.GetParameterData (base_method);
3925                 
3926                         if (cand_pd.Count != base_pd.Count)
3927                                 return false;
3928
3929                         for (int j = 0; j < cand_pd.Count; ++j) 
3930                         {
3931                                 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
3932                                 Parameter.Modifier bm = base_pd.ParameterModifier (j);
3933                                 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
3934                                 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
3935
3936                                 if (cm != bm || ct != bt)
3937                                         return false;
3938                         }
3939
3940                         return true;
3941                 }
3942                 
3943                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3944                 {
3945                         MemberInfo [] miset;
3946                         MethodGroupExpr union;
3947
3948                         if (mg1 == null) {
3949                                 if (mg2 == null)
3950                                         return null;
3951                                 return (MethodGroupExpr) mg2;
3952                         } else {
3953                                 if (mg2 == null)
3954                                         return (MethodGroupExpr) mg1;
3955                         }
3956                         
3957                         MethodGroupExpr left_set = null, right_set = null;
3958                         int length1 = 0, length2 = 0;
3959                         
3960                         left_set = (MethodGroupExpr) mg1;
3961                         length1 = left_set.Methods.Length;
3962                         
3963                         right_set = (MethodGroupExpr) mg2;
3964                         length2 = right_set.Methods.Length;
3965                         
3966                         ArrayList common = new ArrayList ();
3967
3968                         foreach (MethodBase r in right_set.Methods){
3969                                 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
3970                                         common.Add (r);
3971                         }
3972
3973                         miset = new MemberInfo [length1 + length2 - common.Count];
3974                         left_set.Methods.CopyTo (miset, 0);
3975                         
3976                         int k = length1;
3977
3978                         foreach (MethodBase r in right_set.Methods) {
3979                                 if (!common.Contains (r))
3980                                         miset [k++] = r;
3981                         }
3982
3983                         union = new MethodGroupExpr (miset, mg1.Type, loc);
3984                         
3985                         return union;
3986                 }               
3987
3988                 static Type MoreSpecific (Type p, Type q)
3989                 {
3990                         if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
3991                                 return q;
3992                         if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
3993                                 return p;
3994
3995                         if (TypeManager.HasElementType (p)) 
3996                         {
3997                                 Type pe = TypeManager.GetElementType (p);
3998                                 Type qe = TypeManager.GetElementType (q);
3999                                 Type specific = MoreSpecific (pe, qe);
4000                                 if (specific == pe)
4001                                         return p;
4002                                 if (specific == qe)
4003                                         return q;
4004                         } 
4005                         else if (TypeManager.IsGenericType (p)) 
4006                         {
4007                                 Type[] pargs = TypeManager.GetTypeArguments (p);
4008                                 Type[] qargs = TypeManager.GetTypeArguments (q);
4009
4010                                 bool p_specific_at_least_once = false;
4011                                 bool q_specific_at_least_once = false;
4012
4013                                 for (int i = 0; i < pargs.Length; i++) 
4014                                 {
4015                                         Type specific = MoreSpecific (pargs [i], qargs [i]);
4016                                         if (specific == pargs [i])
4017                                                 p_specific_at_least_once = true;
4018                                         if (specific == qargs [i])
4019                                                 q_specific_at_least_once = true;
4020                                 }
4021
4022                                 if (p_specific_at_least_once && !q_specific_at_least_once)
4023                                         return p;
4024                                 if (!p_specific_at_least_once && q_specific_at_least_once)
4025                                         return q;
4026                         }
4027
4028                         return null;
4029                 }
4030
4031                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4032                 {
4033                         base.MutateHoistedGenericType (storey);
4034
4035                         MethodInfo mi = best_candidate as MethodInfo;
4036                         if (mi != null) {
4037                                 best_candidate = storey.MutateGenericMethod (mi);
4038                                 return;
4039                         }
4040
4041                         best_candidate = storey.MutateConstructor ((ConstructorInfo) this);
4042                 }
4043
4044                 /// <summary>
4045                 ///   Find the Applicable Function Members (7.4.2.1)
4046                 ///
4047                 ///   me: Method Group expression with the members to select.
4048                 ///       it might contain constructors or methods (or anything
4049                 ///       that maps to a method).
4050                 ///
4051                 ///   Arguments: ArrayList containing resolved Argument objects.
4052                 ///
4053                 ///   loc: The location if we want an error to be reported, or a Null
4054                 ///        location for "probing" purposes.
4055                 ///
4056                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4057                 ///            that is the best match of me on Arguments.
4058                 ///
4059                 /// </summary>
4060                 public virtual MethodGroupExpr OverloadResolve (EmitContext ec, ref ArrayList Arguments,
4061                         bool may_fail, Location loc)
4062                 {
4063                         bool method_params = false;
4064                         Type applicable_type = null;
4065                         int arg_count = 0;
4066                         ArrayList candidates = new ArrayList (2);
4067                         ArrayList candidate_overrides = null;
4068
4069                         //
4070                         // Used to keep a map between the candidate
4071                         // and whether it is being considered in its
4072                         // normal or expanded form
4073                         //
4074                         // false is normal form, true is expanded form
4075                         //
4076                         Hashtable candidate_to_form = null;
4077
4078                         if (Arguments != null)
4079                                 arg_count = Arguments.Count;
4080
4081                         if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
4082                                 if (!may_fail)
4083                                         Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
4084                                 return null;
4085                         }
4086
4087                         int nmethods = Methods.Length;
4088
4089                         if (!IsBase) {
4090                                 //
4091                                 // Methods marked 'override' don't take part in 'applicable_type'
4092                                 // computation, nor in the actual overload resolution.
4093                                 // However, they still need to be emitted instead of a base virtual method.
4094                                 // So, we salt them away into the 'candidate_overrides' array.
4095                                 //
4096                                 // In case of reflected methods, we replace each overriding method with
4097                                 // its corresponding base virtual method.  This is to improve compatibility
4098                                 // with non-C# libraries which change the visibility of overrides (#75636)
4099                                 //
4100                                 int j = 0;
4101                                 for (int i = 0; i < Methods.Length; ++i) {
4102                                         MethodBase m = Methods [i];
4103                                         if (TypeManager.IsOverride (m)) {
4104                                                 if (candidate_overrides == null)
4105                                                         candidate_overrides = new ArrayList ();
4106                                                 candidate_overrides.Add (m);
4107                                                 m = TypeManager.TryGetBaseDefinition (m);
4108                                         }
4109                                         if (m != null)
4110                                                 Methods [j++] = m;
4111                                 }
4112                                 nmethods = j;
4113                         }
4114
4115                         //
4116                         // Enable message recording, it's used mainly by lambda expressions
4117                         //
4118                         Report.IMessageRecorder msg_recorder = new Report.MessageRecorder ();
4119                         Report.IMessageRecorder prev_recorder = Report.SetMessageRecorder (msg_recorder);
4120
4121                         //
4122                         // First we construct the set of applicable methods
4123                         //
4124                         bool is_sorted = true;
4125                         int best_candidate_rate = int.MaxValue;
4126                         for (int i = 0; i < nmethods; i++) {
4127                                 Type decl_type = Methods [i].DeclaringType;
4128
4129                                 //
4130                                 // If we have already found an applicable method
4131                                 // we eliminate all base types (Section 14.5.5.1)
4132                                 //
4133                                 if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
4134                                         continue;
4135
4136                                 //
4137                                 // Check if candidate is applicable (section 14.4.2.1)
4138                                 //
4139                                 bool params_expanded_form = false;
4140                                 int candidate_rate = IsApplicable (ec, Arguments, arg_count, ref Methods [i], ref params_expanded_form);
4141
4142                                 if (candidate_rate < best_candidate_rate) {
4143                                         best_candidate_rate = candidate_rate;
4144                                         best_candidate = Methods [i];
4145                                 }
4146                                 
4147                                 if (params_expanded_form) {
4148                                         if (candidate_to_form == null)
4149                                                 candidate_to_form = new PtrHashtable ();
4150                                         MethodBase candidate = Methods [i];
4151                                         candidate_to_form [candidate] = candidate;
4152                                 }
4153
4154                                 if (candidate_rate != 0) {
4155                                         if (msg_recorder != null)
4156                                                 msg_recorder.EndSession ();
4157                                         continue;
4158                                 }
4159
4160                                 msg_recorder = null;
4161                                 candidates.Add (Methods [i]);
4162
4163                                 if (applicable_type == null)
4164                                         applicable_type = decl_type;
4165                                 else if (applicable_type != decl_type) {
4166                                         is_sorted = false;
4167                                         if (IsAncestralType (applicable_type, decl_type))
4168                                                 applicable_type = decl_type;
4169                                 }
4170                         }
4171
4172                         Report.SetMessageRecorder (prev_recorder);
4173                         if (msg_recorder != null && !msg_recorder.IsEmpty) {
4174                                 if (!may_fail)
4175                                         msg_recorder.PrintMessages ();
4176
4177                                 return null;
4178                         }
4179                         
4180                         int candidate_top = candidates.Count;
4181
4182                         if (applicable_type == null) {
4183                                 //
4184                                 // When we found a top level method which does not match and it's 
4185                                 // not an extension method. We start extension methods lookup from here
4186                                 //
4187                                 if (InstanceExpression != null) {
4188                                         ExtensionMethodGroupExpr ex_method_lookup = ec.TypeContainer.LookupExtensionMethod (type, Name, loc);
4189                                         if (ex_method_lookup != null) {
4190                                                 ex_method_lookup.ExtensionExpression = InstanceExpression;
4191                                                 ex_method_lookup.SetTypeArguments (type_arguments);
4192                                                 return ex_method_lookup.OverloadResolve (ec, ref Arguments, may_fail, loc);
4193                                         }
4194                                 }
4195                                 
4196                                 if (may_fail)
4197                                         return null;
4198
4199                                 //
4200                                 // Okay so we have failed to find exact match so we
4201                                 // return error info about the closest match
4202                                 //
4203                                 if (best_candidate != null) {
4204                                         if (CustomErrorHandler != null) {
4205                                                 if (CustomErrorHandler.NoExactMatch (ec, best_candidate))
4206                                                         return null;
4207                                         }
4208
4209                                         ParameterData pd = TypeManager.GetParameterData (best_candidate);
4210                                         bool cand_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4211                                         if (arg_count == pd.Count || pd.HasParams) {
4212                                                 if (TypeManager.IsGenericMethodDefinition (best_candidate)) {
4213                                                         if (type_arguments == null) {
4214                                                                 Report.Error (411, loc,
4215                                                                         "The type arguments for method `{0}' cannot be inferred from " +
4216                                                                         "the usage. Try specifying the type arguments explicitly",
4217                                                                         TypeManager.CSharpSignature (best_candidate));
4218                                                                 return null;
4219                                                         }
4220                                                                 
4221                                                         Type [] g_args = TypeManager.GetGenericArguments (best_candidate);
4222                                                         if (type_arguments.Count != g_args.Length) {
4223                                                                 Report.SymbolRelatedToPreviousError (best_candidate);
4224                                                                 Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
4225                                                                         TypeManager.CSharpSignature (best_candidate),
4226                                                                         g_args.Length.ToString ());
4227                                                                 return null;
4228                                                         }
4229                                                 } else {
4230                                                         if (type_arguments != null && !TypeManager.IsGenericMethod (best_candidate)) {
4231                                                                 Namespace.Error_TypeArgumentsCannotBeUsed (best_candidate, loc);
4232                                                                 return null;
4233                                                         }
4234                                                 }
4235                                                 
4236                                                 if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate, cand_params, may_fail, loc))
4237                                                         return null;
4238                                         }
4239                                 }
4240
4241                                 if (almost_matched_members.Count != 0) {
4242                                         Error_MemberLookupFailed (ec.ContainerType, type, type, ".ctor",
4243                                         null, MemberTypes.Constructor, AllBindingFlags);
4244                                         return null;
4245                                 }
4246                                 
4247                                 //
4248                                 // We failed to find any method with correct argument count
4249                                 //
4250                                 if (Name == ConstructorInfo.ConstructorName) {
4251                                         Report.SymbolRelatedToPreviousError (type);
4252                                         Report.Error (1729, loc,
4253                                                 "The type `{0}' does not contain a constructor that takes `{1}' arguments",
4254                                                 TypeManager.CSharpName (type), arg_count);
4255                                 } else {
4256                                         Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
4257                                                 Name, arg_count.ToString ());
4258                                 }
4259                                 
4260                                 return null;
4261                         }
4262
4263                         if (!is_sorted) {
4264                                 //
4265                                 // At this point, applicable_type is _one_ of the most derived types
4266                                 // in the set of types containing the methods in this MethodGroup.
4267                                 // Filter the candidates so that they only contain methods from the
4268                                 // most derived types.
4269                                 //
4270
4271                                 int finalized = 0; // Number of finalized candidates
4272
4273                                 do {
4274                                         // Invariant: applicable_type is a most derived type
4275                                         
4276                                         // We'll try to complete Section 14.5.5.1 for 'applicable_type' by 
4277                                         // eliminating all it's base types.  At the same time, we'll also move
4278                                         // every unrelated type to the end of the array, and pick the next
4279                                         // 'applicable_type'.
4280
4281                                         Type next_applicable_type = null;
4282                                         int j = finalized; // where to put the next finalized candidate
4283                                         int k = finalized; // where to put the next undiscarded candidate
4284                                         for (int i = finalized; i < candidate_top; ++i) {
4285                                                 MethodBase candidate = (MethodBase) candidates [i];
4286                                                 Type decl_type = candidate.DeclaringType;
4287
4288                                                 if (decl_type == applicable_type) {
4289                                                         candidates [k++] = candidates [j];
4290                                                         candidates [j++] = candidates [i];
4291                                                         continue;
4292                                                 }
4293
4294                                                 if (IsAncestralType (decl_type, applicable_type))
4295                                                         continue;
4296
4297                                                 if (next_applicable_type != null &&
4298                                                         IsAncestralType (decl_type, next_applicable_type))
4299                                                         continue;
4300
4301                                                 candidates [k++] = candidates [i];
4302
4303                                                 if (next_applicable_type == null ||
4304                                                         IsAncestralType (next_applicable_type, decl_type))
4305                                                         next_applicable_type = decl_type;
4306                                         }
4307
4308                                         applicable_type = next_applicable_type;
4309                                         finalized = j;
4310                                         candidate_top = k;
4311                                 } while (applicable_type != null);
4312                         }
4313
4314                         //
4315                         // Now we actually find the best method
4316                         //
4317
4318                         best_candidate = (MethodBase) candidates [0];
4319                         if (delegate_type == null)
4320                                 method_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4321
4322                         for (int ix = 1; ix < candidate_top; ix++) {
4323                                 MethodBase candidate = (MethodBase) candidates [ix];
4324
4325                                 if (candidate == best_candidate)
4326                                         continue;
4327
4328                                 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4329
4330                                 if (BetterFunction (ec, Arguments, arg_count, 
4331                                         candidate, cand_params,
4332                                         best_candidate, method_params)) {
4333                                         best_candidate = candidate;
4334                                         method_params = cand_params;
4335                                 }
4336                         }
4337                         //
4338                         // Now check that there are no ambiguities i.e the selected method
4339                         // should be better than all the others
4340                         //
4341                         MethodBase ambiguous = null;
4342                         for (int ix = 1; ix < candidate_top; ix++) {
4343                                 MethodBase candidate = (MethodBase) candidates [ix];
4344
4345                                 if (candidate == best_candidate)
4346                                         continue;
4347
4348                                 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4349                                 if (!BetterFunction (ec, Arguments, arg_count,
4350                                         best_candidate, method_params,
4351                                         candidate, cand_params)) 
4352                                 {
4353                                         if (!may_fail)
4354                                                 Report.SymbolRelatedToPreviousError (candidate);
4355                                         ambiguous = candidate;
4356                                 }
4357                         }
4358
4359                         if (ambiguous != null) {
4360                                 Report.SymbolRelatedToPreviousError (best_candidate);
4361                                 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
4362                                         TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (best_candidate));
4363                                 return this;
4364                         }
4365
4366                         //
4367                         // If the method is a virtual function, pick an override closer to the LHS type.
4368                         //
4369                         if (!IsBase && best_candidate.IsVirtual) {
4370                                 if (TypeManager.IsOverride (best_candidate))
4371                                         throw new InternalErrorException (
4372                                                 "Should not happen.  An 'override' method took part in overload resolution: " + best_candidate);
4373
4374                                 if (candidate_overrides != null) {
4375                                         Type[] gen_args = null;
4376                                         bool gen_override = false;
4377                                         if (TypeManager.IsGenericMethod (best_candidate))
4378                                                 gen_args = TypeManager.GetGenericArguments (best_candidate);
4379
4380                                         foreach (MethodBase candidate in candidate_overrides) {
4381                                                 if (TypeManager.IsGenericMethod (candidate)) {
4382                                                         if (gen_args == null)
4383                                                                 continue;
4384
4385                                                         if (gen_args.Length != TypeManager.GetGenericArguments (candidate).Length)
4386                                                                 continue;
4387                                                 } else {
4388                                                         if (gen_args != null)
4389                                                                 continue;
4390                                                 }
4391                                                 
4392                                                 if (IsOverride (candidate, best_candidate)) {
4393                                                         gen_override = true;
4394                                                         best_candidate = candidate;
4395                                                 }
4396                                         }
4397
4398                                         if (gen_override && gen_args != null) {
4399 #if GMCS_SOURCE
4400                                                 best_candidate = ((MethodInfo) best_candidate).MakeGenericMethod (gen_args);
4401 #endif                                          
4402                                         }
4403                                 }
4404                         }
4405
4406                         //
4407                         // And now check if the arguments are all
4408                         // compatible, perform conversions if
4409                         // necessary etc. and return if everything is
4410                         // all right
4411                         //
4412                         if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate,
4413                                 method_params, may_fail, loc))
4414                                 return null;
4415
4416                         if (best_candidate == null)
4417                                 return null;
4418
4419                         MethodBase the_method = TypeManager.DropGenericMethodArguments (best_candidate);
4420 #if GMCS_SOURCE
4421                         if (the_method.IsGenericMethodDefinition &&
4422                             !ConstraintChecker.CheckConstraints (ec, the_method, best_candidate, loc))
4423                                 return null;
4424 #endif
4425
4426                         IMethodData data = TypeManager.GetMethod (the_method);
4427                         if (data != null)
4428                                 data.SetMemberIsUsed ();
4429
4430                         return this;
4431                 }
4432                 
4433                 public override void SetTypeArguments (TypeArguments ta)
4434                 {
4435                         type_arguments = ta;
4436                 }
4437
4438                 public bool VerifyArgumentsCompat (EmitContext ec, ref ArrayList arguments,
4439                                                           int arg_count, MethodBase method,
4440                                                           bool chose_params_expanded,
4441                                                           bool may_fail, Location loc)
4442                 {
4443                         ParameterData pd = TypeManager.GetParameterData (method);
4444
4445                         int errors = Report.Errors;
4446                         Parameter.Modifier p_mod = 0;
4447                         Type pt = null;
4448                         int a_idx = 0, a_pos = 0;
4449                         Argument a = null;
4450                         ArrayList params_initializers = null;
4451
4452                         for (; a_idx < arg_count; a_idx++, ++a_pos) {
4453                                 a = (Argument) arguments [a_idx];
4454                                 if (p_mod != Parameter.Modifier.PARAMS) {
4455                                         p_mod = pd.ParameterModifier (a_idx);
4456                                         pt = pd.ParameterType (a_idx);
4457
4458                                         if (p_mod == Parameter.Modifier.ARGLIST) {
4459                                                 if (a.Type != TypeManager.runtime_argument_handle_type)
4460                                                         break;
4461                                                 continue;
4462                                         }
4463
4464                                         if (pt.IsPointer && !ec.InUnsafe) {
4465                                                 if (may_fail)
4466                                                         return false;
4467
4468                                                 UnsafeError (loc);
4469                                         }
4470
4471                                         if (p_mod == Parameter.Modifier.PARAMS) {
4472                                                 if (chose_params_expanded) {
4473                                                         params_initializers = new ArrayList (arg_count - a_idx);
4474                                                         pt = TypeManager.GetElementType (pt);
4475                                                 }
4476                                         } else if (p_mod != 0) {
4477                                                 pt = TypeManager.GetElementType (pt);
4478                                         }
4479                                 }
4480
4481                                 //
4482                                 // Types have to be identical when ref or out modifer is used 
4483                                 //
4484                                 if (a.Modifier != 0 || (p_mod & ~Parameter.Modifier.PARAMS) != 0) {
4485                                         if ((p_mod & ~Parameter.Modifier.PARAMS) != a.Modifier)
4486                                                 break;
4487
4488                                         if (!TypeManager.IsEqual (a.Expr.Type, pt))
4489                                                 break;
4490
4491                                         continue;
4492                                 }
4493
4494                                 Expression conv;
4495                                 if (TypeManager.IsEqual (a.Type, pt)) {
4496                                         conv = a.Expr;
4497                                 } else {
4498                                         conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
4499                                         if (conv == null)
4500                                                 break;
4501                                 }
4502
4503                                 //
4504                                 // Convert params arguments to an array initializer
4505                                 //
4506                                 if (params_initializers != null) {
4507                                         // we choose to use 'a.Expr' rather than 'conv' so that
4508                                         // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
4509                                         params_initializers.Add (a.Expr);
4510                                         arguments.RemoveAt (a_idx--);
4511                                         --arg_count;
4512                                         continue;
4513                                 }
4514
4515                                 // Update the argument with the implicit conversion
4516                                 a.Expr = conv;
4517                         }
4518
4519                         //
4520                         // Fill not provided arguments required by params modifier
4521                         //
4522                         if (params_initializers == null && pd.HasParams && arg_count < pd.Count && a_idx + 1 == pd.Count) {
4523                                 if (arguments == null)
4524                                         arguments = new ArrayList (1);
4525
4526                                 pt = pd.Types [GetApplicableParametersCount (method, pd) - 1];
4527                                 pt = TypeManager.GetElementType (pt);
4528                                 params_initializers = new ArrayList (0);
4529                         }
4530
4531                         if (a_idx == arg_count) {
4532                                 //
4533                                 // Append an array argument with all params arguments
4534                                 //
4535                                 if (params_initializers != null) {
4536                                         arguments.Add (new Argument (
4537                                                 new ArrayCreation (new TypeExpression (pt, loc), "[]",
4538                                                 params_initializers, loc).Resolve (ec)));
4539                                 }
4540                                 return true;
4541                         }
4542
4543                         if (!may_fail && Report.Errors == errors) {
4544                                 if (CustomErrorHandler != null)
4545                                         CustomErrorHandler.NoExactMatch (ec, best_candidate);
4546                                 else
4547                                         Error_InvalidArguments (ec, loc, a_pos, method, a, pd, pt);
4548                         }
4549                         return false;
4550                 }
4551         }
4552
4553         public class ConstantExpr : MemberExpr
4554         {
4555                 FieldInfo constant;
4556
4557                 public ConstantExpr (FieldInfo constant, Location loc)
4558                 {
4559                         this.constant = constant;
4560                         this.loc = loc;
4561                 }
4562
4563                 public override string Name {
4564                         get { throw new NotImplementedException (); }
4565                 }
4566
4567                 public override bool IsInstance {
4568                         get { return !IsStatic; }
4569                 }
4570
4571                 public override bool IsStatic {
4572                         get { return constant.IsStatic; }
4573                 }
4574
4575                 public override Type DeclaringType {
4576                         get { return constant.DeclaringType; }
4577                 }
4578
4579                 public override MemberExpr ResolveMemberAccess (EmitContext ec, Expression left, Location loc, SimpleName original)
4580                 {
4581                         constant = TypeManager.GetGenericFieldDefinition (constant);
4582
4583                         IConstant ic = TypeManager.GetConstant (constant);
4584                         if (ic == null) {
4585                                 if (constant.IsLiteral) {
4586                                         ic = new ExternalConstant (constant);
4587                                 } else {
4588                                         ic = ExternalConstant.CreateDecimal (constant);
4589                                         // HACK: decimal field was not resolved as constant
4590                                         if (ic == null)
4591                                                 return new FieldExpr (constant, loc).ResolveMemberAccess (ec, left, loc, original);
4592                                 }
4593                                 TypeManager.RegisterConstant (constant, ic);
4594                         }
4595
4596                         return base.ResolveMemberAccess (ec, left, loc, original);
4597                 }
4598
4599                 public override Expression CreateExpressionTree (EmitContext ec)
4600                 {
4601                         throw new NotSupportedException ("ET");
4602                 }
4603
4604                 public override Expression DoResolve (EmitContext ec)
4605                 {
4606                         IConstant ic = TypeManager.GetConstant (constant);
4607                         if (ic.ResolveValue ()) {
4608                                 if (!ec.IsInObsoleteScope)
4609                                         ic.CheckObsoleteness (loc);
4610                         }
4611
4612                         return ic.CreateConstantReference (loc);
4613                 }
4614
4615                 public override void Emit (EmitContext ec)
4616                 {
4617                         throw new NotSupportedException ();
4618                 }
4619
4620                 public override string GetSignatureForError ()
4621                 {
4622                         return TypeManager.GetFullNameSignature (constant);
4623                 }
4624         }
4625
4626         /// <summary>
4627         ///   Fully resolved expression that evaluates to a Field
4628         /// </summary>
4629         public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
4630                 public FieldInfo FieldInfo;
4631                 readonly Type constructed_generic_type;
4632                 VariableInfo variable_info;
4633                 
4634                 LocalTemporary temp;
4635                 bool prepared;
4636                 bool in_initializer;
4637
4638                 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
4639                         this (fi, l)
4640                 {
4641                         this.in_initializer = in_initializer;
4642                 }
4643                 
4644                 public FieldExpr (FieldInfo fi, Location l)
4645                 {
4646                         FieldInfo = fi;
4647                         eclass = ExprClass.Variable;
4648                         type = TypeManager.TypeToCoreType (fi.FieldType);
4649                         loc = l;
4650                 }
4651
4652                 public FieldExpr (FieldInfo fi, Type genericType, Location l)
4653                         : this (fi, l)
4654                 {
4655                         this.constructed_generic_type = genericType;
4656                 }
4657
4658                 public override string Name {
4659                         get {
4660                                 return FieldInfo.Name;
4661                         }
4662                 }
4663
4664                 public override bool IsInstance {
4665                         get {
4666                                 return !FieldInfo.IsStatic;
4667                         }
4668                 }
4669
4670                 public override bool IsStatic {
4671                         get {
4672                                 return FieldInfo.IsStatic;
4673                         }
4674                 }
4675
4676                 public override Type DeclaringType {
4677                         get {
4678                                 return FieldInfo.DeclaringType;
4679                         }
4680                 }
4681
4682                 public override string GetSignatureForError ()
4683                 {
4684                         return TypeManager.GetFullNameSignature (FieldInfo);
4685                 }
4686
4687                 public VariableInfo VariableInfo {
4688                         get {
4689                                 return variable_info;
4690                         }
4691                 }
4692
4693                 public override MemberExpr ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
4694                                                                 SimpleName original)
4695                 {
4696                         FieldInfo fi = TypeManager.GetGenericFieldDefinition (FieldInfo);
4697                         Type t = fi.FieldType;
4698
4699                         if (t.IsPointer && !ec.InUnsafe) {
4700                                 UnsafeError (loc);
4701                         }
4702
4703                         return base.ResolveMemberAccess (ec, left, loc, original);
4704                 }
4705
4706                 public override Expression CreateExpressionTree (EmitContext ec)
4707                 {
4708                         Expression instance;
4709                         if (InstanceExpression == null) {
4710                                 instance = new NullLiteral (loc);
4711                         } else {
4712                                 instance = InstanceExpression.CreateExpressionTree (ec);
4713                         }
4714
4715                         ArrayList args = new ArrayList (2);
4716                         args.Add (new Argument (instance));
4717                         args.Add (new Argument (CreateTypeOfExpression ()));
4718                         return CreateExpressionFactoryCall ("Field", args);
4719                 }
4720
4721                 public Expression CreateTypeOfExpression ()
4722                 {
4723                         return new TypeOfField (FieldInfo, loc);
4724                 }
4725
4726                 override public Expression DoResolve (EmitContext ec)
4727                 {
4728                         return DoResolve (ec, false, false);
4729                 }
4730
4731                 Expression DoResolve (EmitContext ec, bool lvalue_instance, bool out_access)
4732                 {
4733                         if (!FieldInfo.IsStatic){
4734                                 if (InstanceExpression == null){
4735                                         //
4736                                         // This can happen when referencing an instance field using
4737                                         // a fully qualified type expression: TypeName.InstanceField = xxx
4738                                         // 
4739                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
4740                                         return null;
4741                                 }
4742
4743                                 // Resolve the field's instance expression while flow analysis is turned
4744                                 // off: when accessing a field "a.b", we must check whether the field
4745                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4746
4747                                 if (lvalue_instance) {
4748                                         using (ec.With (EmitContext.Flags.DoFlowAnalysis, false)) {
4749                                                 Expression right_side =
4750                                                         out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
4751                                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side, loc);
4752                                         }
4753                                 } else {
4754                                         ResolveFlags rf = ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis;
4755                                         InstanceExpression = InstanceExpression.Resolve (ec, rf);
4756                                 }
4757
4758                                 if (InstanceExpression == null)
4759                                         return null;
4760
4761                                 using (ec.Set (EmitContext.Flags.OmitStructFlowAnalysis)) {
4762                                         InstanceExpression.CheckMarshalByRefAccess (ec);
4763                                 }
4764                         }
4765
4766                         if (!in_initializer && !ec.IsInFieldInitializer) {
4767                                 ObsoleteAttribute oa;
4768                                 FieldBase f = TypeManager.GetField (FieldInfo);
4769                                 if (f != null) {
4770                                         if (!ec.IsInObsoleteScope)
4771                                                 f.CheckObsoleteness (loc);
4772                                 
4773                                         // To be sure that type is external because we do not register generated fields
4774                                 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {                                
4775                                         oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
4776                                         if (oa != null)
4777                                                 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
4778                                 }
4779                         }
4780
4781                         IFixedBuffer fb = AttributeTester.GetFixedBuffer (FieldInfo);
4782                         if (fb != null) {
4783                                 if (!ec.InFixedInitializer && ec.ContainerType.IsValueType) {
4784                                         Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
4785                                 }
4786
4787                                 if (InstanceExpression.eclass != ExprClass.Variable) {
4788                                         Report.SymbolRelatedToPreviousError (FieldInfo);
4789                                         Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
4790                                                 TypeManager.GetFullNameSignature (FieldInfo));
4791                                 }
4792                                 
4793                                 return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
4794                         }
4795
4796                         // If the instance expression is a local variable or parameter.
4797                         IVariable var = InstanceExpression as IVariable;
4798                         if (var == null || var.VariableInfo == null)
4799                                 return this;
4800
4801                         VariableInfo vi = var.VariableInfo;
4802                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
4803                                 return null;
4804
4805                         variable_info = vi.GetSubStruct (FieldInfo.Name);
4806                         return this;
4807                 }
4808
4809                 static readonly int [] codes = {
4810                         191,    // instance, write access
4811                         192,    // instance, out access
4812                         198,    // static, write access
4813                         199,    // static, out access
4814                         1648,   // member of value instance, write access
4815                         1649,   // member of value instance, out access
4816                         1650,   // member of value static, write access
4817                         1651    // member of value static, out access
4818                 };
4819
4820                 static readonly string [] msgs = {
4821                         /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
4822                         /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4823                         /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4824                         /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
4825                         /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
4826                         /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4827                         /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4828                         /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
4829                 };
4830
4831                 // The return value is always null.  Returning a value simplifies calling code.
4832                 Expression Report_AssignToReadonly (Expression right_side)
4833                 {
4834                         int i = 0;
4835                         if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
4836                                 i += 1;
4837                         if (IsStatic)
4838                                 i += 2;
4839                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
4840                                 i += 4;
4841                         Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
4842
4843                         return null;
4844                 }
4845                 
4846                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4847                 {
4848                         IVariable var = InstanceExpression as IVariable;
4849                         if (var != null && var.VariableInfo != null)
4850                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
4851
4852                         bool lvalue_instance = !FieldInfo.IsStatic && FieldInfo.DeclaringType.IsValueType;
4853                         bool out_access = right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess;
4854
4855                         Expression e = DoResolve (ec, lvalue_instance, out_access);
4856
4857                         if (e == null)
4858                                 return null;
4859
4860                         FieldBase fb = TypeManager.GetField (FieldInfo);
4861                         if (fb != null)
4862                                 fb.SetAssigned ();
4863
4864                         if (FieldInfo.IsInitOnly) {
4865                                 // InitOnly fields can only be assigned in constructors or initializers
4866                                 if (!ec.IsInFieldInitializer && !ec.IsConstructor)
4867                                         return Report_AssignToReadonly (right_side);
4868
4869                                 if (ec.IsConstructor) {
4870                                         Type ctype = ec.TypeContainer.CurrentType;
4871                                         if (ctype == null)
4872                                                 ctype = ec.ContainerType;
4873
4874                                         // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
4875                                         if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
4876                                                 return Report_AssignToReadonly (right_side);
4877                                         // static InitOnly fields cannot be assigned-to in an instance constructor
4878                                         if (IsStatic && !ec.IsStatic)
4879                                                 return Report_AssignToReadonly (right_side);
4880                                         // instance constructors can't modify InitOnly fields of other instances of the same type
4881                                         if (!IsStatic && !(InstanceExpression is This))
4882                                                 return Report_AssignToReadonly (right_side);
4883                                 }
4884                         }
4885
4886                         if (right_side == EmptyExpression.OutAccess &&
4887                             !IsStatic && !(InstanceExpression is This) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type)) {
4888                                 Report.SymbolRelatedToPreviousError (DeclaringType);
4889                                 Report.Warning (197, 1, loc,
4890                                                 "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",
4891                                                 GetSignatureForError ());
4892                         }
4893
4894                         return this;
4895                 }
4896
4897                 bool is_marshal_by_ref ()
4898                 {
4899                         return !IsStatic && Type.IsValueType && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type);
4900                 }
4901
4902                 public override void CheckMarshalByRefAccess (EmitContext ec)
4903                 {
4904                         if (is_marshal_by_ref () && !(InstanceExpression is This)) {
4905                                 Report.SymbolRelatedToPreviousError (DeclaringType);
4906                                 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",
4907                                                 GetSignatureForError ());
4908                         }
4909                 }
4910
4911                 public override int GetHashCode ()
4912                 {
4913                         return FieldInfo.GetHashCode ();
4914                 }
4915                 
4916                 public bool IsFixed {
4917                         get {
4918                                 IVariable variable = InstanceExpression as IVariable;
4919                                 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
4920                                 // We defer the InstanceExpression check after the variable check to avoid a 
4921                                 // separate null check on InstanceExpression.
4922                                 return variable != null && InstanceExpression.Type.IsValueType && variable.IsFixed;
4923                         }
4924                 }               
4925
4926                 public override bool Equals (object obj)
4927                 {
4928                         FieldExpr fe = obj as FieldExpr;
4929                         if (fe == null)
4930                                 return false;
4931
4932                         if (FieldInfo != fe.FieldInfo)
4933                                 return false;
4934
4935                         if (InstanceExpression == null || fe.InstanceExpression == null)
4936                                 return true;
4937
4938                         return InstanceExpression.Equals (fe.InstanceExpression);
4939                 }
4940                 
4941                 public void Emit (EmitContext ec, bool leave_copy)
4942                 {
4943                         ILGenerator ig = ec.ig;
4944                         bool is_volatile = false;
4945
4946                         FieldBase f = TypeManager.GetField (FieldInfo);
4947                         if (f != null){
4948                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4949                                         is_volatile = true;
4950
4951                                 f.SetMemberIsUsed ();
4952                         }
4953                         
4954                         if (FieldInfo.IsStatic){
4955                                 if (is_volatile)
4956                                         ig.Emit (OpCodes.Volatile);
4957
4958                                 ig.Emit (OpCodes.Ldsfld, GetConstructedFieldInfo ());
4959                         } else {
4960                                 if (!prepared)
4961                                         EmitInstance (ec, false);
4962
4963                                 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
4964                                 if (ff != null) {
4965                                         ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
4966                                         ig.Emit (OpCodes.Ldflda, ff.Element);
4967                                 } else {
4968                                         if (is_volatile)
4969                                                 ig.Emit (OpCodes.Volatile);
4970
4971                                         ig.Emit (OpCodes.Ldfld, GetConstructedFieldInfo ());
4972                                 }
4973                         }
4974
4975                         if (leave_copy) {
4976                                 ec.ig.Emit (OpCodes.Dup);
4977                                 if (!FieldInfo.IsStatic) {
4978                                         temp = new LocalTemporary (this.Type);
4979                                         temp.Store (ec);
4980                                 }
4981                         }
4982                 }
4983
4984                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4985                 {
4986                         FieldAttributes fa = FieldInfo.Attributes;
4987                         bool is_static = (fa & FieldAttributes.Static) != 0;
4988                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
4989                         ILGenerator ig = ec.ig;
4990
4991                         if (is_readonly && !ec.IsConstructor){
4992                                 Report_AssignToReadonly (source);
4993                                 return;
4994                         }
4995
4996                         prepared = prepare_for_load;
4997                         EmitInstance (ec, prepared);
4998
4999                         source.Emit (ec);                       
5000                         if (leave_copy) {
5001                                 ec.ig.Emit (OpCodes.Dup);
5002                                 if (!FieldInfo.IsStatic) {
5003                                         temp = new LocalTemporary (this.Type);
5004                                         temp.Store (ec);
5005                                 }
5006                         }
5007
5008                         FieldBase f = TypeManager.GetField (FieldInfo);
5009                         if (f != null){
5010                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
5011                                         ig.Emit (OpCodes.Volatile);
5012                                         
5013                                 f.SetAssigned ();
5014                         }
5015
5016                         if (is_static)
5017                                 ig.Emit (OpCodes.Stsfld, GetConstructedFieldInfo ());
5018                         else
5019                                 ig.Emit (OpCodes.Stfld, GetConstructedFieldInfo ());
5020                         
5021                         if (temp != null) {
5022                                 temp.Emit (ec);
5023                                 temp.Release (ec);
5024                                 temp = null;
5025                         }
5026                 }
5027
5028                 public override void Emit (EmitContext ec)
5029                 {
5030                         Emit (ec, false);
5031                 }
5032
5033                 public override void EmitSideEffect (EmitContext ec)
5034                 {
5035                         FieldBase f = TypeManager.GetField (FieldInfo);
5036                         bool is_volatile = f != null && (f.ModFlags & Modifiers.VOLATILE) != 0;
5037
5038                         if (is_volatile || is_marshal_by_ref ())
5039                                 base.EmitSideEffect (ec);
5040                 }
5041
5042                 public void AddressOf (EmitContext ec, AddressOp mode)
5043                 {
5044                         ILGenerator ig = ec.ig;
5045
5046                         FieldBase f = TypeManager.GetField (FieldInfo);
5047                         if (f != null){
5048                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
5049                                         Report.Warning (420, 1, loc, "`{0}': A volatile field references will not be treated as volatile", 
5050                                                         f.GetSignatureForError ());
5051                                 }
5052                                         
5053                                 if ((mode & AddressOp.Store) != 0)
5054                                         f.SetAssigned ();
5055                                 if ((mode & AddressOp.Load) != 0)
5056                                         f.SetMemberIsUsed ();
5057                         }
5058
5059                         //
5060                         // Handle initonly fields specially: make a copy and then
5061                         // get the address of the copy.
5062                         //
5063                         bool need_copy;
5064                         if (FieldInfo.IsInitOnly){
5065                                 need_copy = true;
5066                                 if (ec.IsConstructor){
5067                                         if (FieldInfo.IsStatic){
5068                                                 if (ec.IsStatic)
5069                                                         need_copy = false;
5070                                         } else
5071                                                 need_copy = false;
5072                                 }
5073                         } else
5074                                 need_copy = false;
5075                         
5076                         if (need_copy){
5077                                 LocalBuilder local;
5078                                 Emit (ec);
5079                                 local = ig.DeclareLocal (type);
5080                                 ig.Emit (OpCodes.Stloc, local);
5081                                 ig.Emit (OpCodes.Ldloca, local);
5082                                 return;
5083                         }
5084
5085
5086                         if (FieldInfo.IsStatic){
5087                                 ig.Emit (OpCodes.Ldsflda, GetConstructedFieldInfo ());
5088                         } else {
5089                                 if (!prepared)
5090                                         EmitInstance (ec, false);
5091                                 ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
5092                         }
5093                 }
5094
5095                 FieldInfo GetConstructedFieldInfo ()
5096                 {
5097                         if (constructed_generic_type == null)
5098                                 return FieldInfo;
5099 #if GMCS_SOURCE
5100                         return TypeBuilder.GetField (constructed_generic_type, FieldInfo);
5101 #else
5102                         throw new NotSupportedException ();
5103 #endif                  
5104                 }
5105                 
5106                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5107                 {
5108                         FieldInfo = storey.MutateField (FieldInfo);
5109                         base.MutateHoistedGenericType (storey);
5110                 }               
5111         }
5112
5113         
5114         /// <summary>
5115         ///   Expression that evaluates to a Property.  The Assign class
5116         ///   might set the `Value' expression if we are in an assignment.
5117         ///
5118         ///   This is not an LValue because we need to re-write the expression, we
5119         ///   can not take data from the stack and store it.  
5120         /// </summary>
5121         public class PropertyExpr : MemberExpr, IAssignMethod {
5122                 public readonly PropertyInfo PropertyInfo;
5123                 MethodInfo getter, setter;
5124                 bool is_static;
5125
5126                 bool resolved;
5127                 
5128                 LocalTemporary temp;
5129                 bool prepared;
5130
5131                 public PropertyExpr (Type container_type, PropertyInfo pi, Location l)
5132                 {
5133                         PropertyInfo = pi;
5134                         eclass = ExprClass.PropertyAccess;
5135                         is_static = false;
5136                         loc = l;
5137
5138                         type = TypeManager.TypeToCoreType (pi.PropertyType);
5139
5140                         ResolveAccessors (container_type);
5141                 }
5142
5143                 public override string Name {
5144                         get {
5145                                 return PropertyInfo.Name;
5146                         }
5147                 }
5148
5149                 public override bool IsInstance {
5150                         get {
5151                                 return !is_static;
5152                         }
5153                 }
5154
5155                 public override bool IsStatic {
5156                         get {
5157                                 return is_static;
5158                         }
5159                 }
5160
5161                 public override Expression CreateExpressionTree (EmitContext ec)
5162                 {
5163                         ArrayList args;
5164                         if (IsSingleDimensionalArrayLength ()) {
5165                                 args = new ArrayList (1);
5166                                 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5167                                 return CreateExpressionFactoryCall ("ArrayLength", args);
5168                         }
5169
5170                         if (is_base) {
5171                                 Error_BaseAccessInExpressionTree (loc);
5172                                 return null;
5173                         }
5174
5175                         args = new ArrayList (2);
5176                         if (InstanceExpression == null)
5177                                 args.Add (new Argument (new NullLiteral (loc)));
5178                         else
5179                                 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5180                         args.Add (new Argument (new TypeOfMethodInfo (getter, loc)));
5181                         return CreateExpressionFactoryCall ("Property", args);
5182                 }
5183
5184                 public Expression CreateSetterTypeOfExpression ()
5185                 {
5186                         return new TypeOfMethodInfo (setter, loc);
5187                 }
5188
5189                 public override Type DeclaringType {
5190                         get {
5191                                 return PropertyInfo.DeclaringType;
5192                         }
5193                 }
5194
5195                 public override string GetSignatureForError ()
5196                 {
5197                         return TypeManager.GetFullNameSignature (PropertyInfo);
5198                 }
5199
5200                 void FindAccessors (Type invocation_type)
5201                 {
5202                         const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
5203                                 BindingFlags.Static | BindingFlags.Instance |
5204                                 BindingFlags.DeclaredOnly;
5205
5206                         Type current = PropertyInfo.DeclaringType;
5207                         for (; current != null; current = current.BaseType) {
5208                                 MemberInfo[] group = TypeManager.MemberLookup (
5209                                         invocation_type, invocation_type, current,
5210                                         MemberTypes.Property, flags, PropertyInfo.Name, null);
5211
5212                                 if (group == null)
5213                                         continue;
5214
5215                                 if (group.Length != 1)
5216                                         // Oooops, can this ever happen ?
5217                                         return;
5218
5219                                 PropertyInfo pi = (PropertyInfo) group [0];
5220
5221                                 if (getter == null)
5222                                         getter = pi.GetGetMethod (true);
5223
5224                                 if (setter == null)
5225                                         setter = pi.GetSetMethod (true);
5226
5227                                 MethodInfo accessor = getter != null ? getter : setter;
5228
5229                                 if (!accessor.IsVirtual)
5230                                         return;
5231                         }
5232                 }
5233
5234                 //
5235                 // We also perform the permission checking here, as the PropertyInfo does not
5236                 // hold the information for the accessibility of its setter/getter
5237                 //
5238                 // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
5239                 void ResolveAccessors (Type container_type)
5240                 {
5241                         FindAccessors (container_type);
5242
5243                         if (getter != null) {
5244                                 MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
5245                                 IMethodData md = TypeManager.GetMethod (the_getter);
5246                                 if (md != null)
5247                                         md.SetMemberIsUsed ();
5248
5249                                 is_static = getter.IsStatic;
5250                         }
5251
5252                         if (setter != null) {
5253                                 MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
5254                                 IMethodData md = TypeManager.GetMethod (the_setter);
5255                                 if (md != null)
5256                                         md.SetMemberIsUsed ();
5257
5258                                 is_static = setter.IsStatic;
5259                         }
5260                 }
5261
5262                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5263                 {
5264                         if (InstanceExpression != null)
5265                                 InstanceExpression.MutateHoistedGenericType (storey);
5266
5267                         type = storey.MutateType (type);
5268                         getter = storey.MutateGenericMethod (getter);
5269                 }
5270
5271                 bool InstanceResolve (EmitContext ec, bool lvalue_instance, bool must_do_cs1540_check)
5272                 {
5273                         if (is_static) {
5274                                 InstanceExpression = null;
5275                                 return true;
5276                         }
5277
5278                         if (InstanceExpression == null) {
5279                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5280                                 return false;
5281                         }
5282
5283                         InstanceExpression = InstanceExpression.DoResolve (ec);
5284                         if (lvalue_instance && InstanceExpression != null)
5285                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, EmptyExpression.LValueMemberAccess, loc);
5286
5287                         if (InstanceExpression == null)
5288                                 return false;
5289
5290                         InstanceExpression.CheckMarshalByRefAccess (ec);
5291
5292                         if (must_do_cs1540_check && (InstanceExpression != EmptyExpression.Null) &&
5293                             !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.ContainerType) &&
5294                             !TypeManager.IsNestedChildOf (ec.ContainerType, InstanceExpression.Type) &&
5295                             !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.ContainerType)) {
5296                                 Report.SymbolRelatedToPreviousError (PropertyInfo);
5297                                 Error_CannotAccessProtected (loc, PropertyInfo, InstanceExpression.Type, ec.ContainerType);
5298                                 return false;
5299                         }
5300
5301                         return true;
5302                 }
5303
5304                 void Error_PropertyNotFound (MethodInfo mi, bool getter)
5305                 {
5306                         // TODO: correctly we should compare arguments but it will lead to bigger changes
5307                         if (mi is MethodBuilder) {
5308                                 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
5309                                 return;
5310                         }
5311                         
5312                         StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
5313                         sig.Append ('.');
5314                         ParameterData iparams = TypeManager.GetParameterData (mi);
5315                         sig.Append (getter ? "get_" : "set_");
5316                         sig.Append (Name);
5317                         sig.Append (iparams.GetSignatureForError ());
5318
5319                         Report.SymbolRelatedToPreviousError (mi);
5320                         Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
5321                                 Name, sig.ToString ());
5322                 }
5323
5324                 public bool IsAccessibleFrom (Type invocation_type, bool lvalue)
5325                 {
5326                         bool dummy;
5327                         MethodInfo accessor = lvalue ? setter : getter;
5328                         if (accessor == null && lvalue)
5329                                 accessor = getter;
5330                         return accessor != null && IsAccessorAccessible (invocation_type, accessor, out dummy);
5331                 }
5332
5333                 bool IsSingleDimensionalArrayLength ()
5334                 {
5335                         if (DeclaringType != TypeManager.array_type || getter == null || Name != "Length")
5336                                 return false;
5337
5338                         string t_name = InstanceExpression.Type.Name;
5339                         int t_name_len = t_name.Length;
5340                         return t_name_len > 2 && t_name [t_name_len - 2] == '[';
5341                 }
5342
5343                 override public Expression DoResolve (EmitContext ec)
5344                 {
5345                         if (resolved)
5346                                 return this;
5347
5348                         if (getter != null){
5349                                 if (TypeManager.GetParameterData (getter).Count != 0){
5350                                         Error_PropertyNotFound (getter, true);
5351                                         return null;
5352                                 }
5353                         }
5354
5355                         if (getter == null){
5356                                 //
5357                                 // The following condition happens if the PropertyExpr was
5358                                 // created, but is invalid (ie, the property is inaccessible),
5359                                 // and we did not want to embed the knowledge about this in
5360                                 // the caller routine.  This only avoids double error reporting.
5361                                 //
5362                                 if (setter == null)
5363                                         return null;
5364
5365                                 if (InstanceExpression != EmptyExpression.Null) {
5366                                         Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
5367                                                 TypeManager.GetFullNameSignature (PropertyInfo));
5368                                         return null;
5369                                 }
5370                         } 
5371
5372                         bool must_do_cs1540_check = false;
5373                         if (getter != null &&
5374                             !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
5375                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
5376                                 if (pm != null && pm.HasCustomAccessModifier) {
5377                                         Report.SymbolRelatedToPreviousError (pm);
5378                                         Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
5379                                                 TypeManager.CSharpSignature (getter));
5380                                 }
5381                                 else {
5382                                         Report.SymbolRelatedToPreviousError (getter);
5383                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
5384                                 }
5385                                 return null;
5386                         }
5387                         
5388                         if (!InstanceResolve (ec, false, must_do_cs1540_check))
5389                                 return null;
5390
5391                         //
5392                         // Only base will allow this invocation to happen.
5393                         //
5394                         if (IsBase && getter.IsAbstract) {
5395                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
5396                                 return null;
5397                         }
5398
5399                         if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
5400                                 UnsafeError (loc);
5401                                 return null;
5402                         }
5403
5404                         resolved = true;
5405
5406                         return this;
5407                 }
5408
5409                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5410                 {
5411                         if (right_side == EmptyExpression.OutAccess) {
5412                                 if (ec.CurrentBlock.Toplevel.GetTransparentIdentifier (PropertyInfo.Name) != null) {
5413                                         Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
5414                                             PropertyInfo.Name);
5415                                 } else {
5416                                         Report.Error (206, loc, "A property or indexer `{0}' may not be passed as `ref' or `out' parameter",
5417                                               GetSignatureForError ());
5418                                 }
5419                                 return null;
5420                         }
5421
5422                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
5423                                 Error_CannotModifyIntermediateExpressionValue (ec);
5424                         }
5425
5426                         if (setter == null){
5427                                 //
5428                                 // The following condition happens if the PropertyExpr was
5429                                 // created, but is invalid (ie, the property is inaccessible),
5430                                 // and we did not want to embed the knowledge about this in
5431                                 // the caller routine.  This only avoids double error reporting.
5432                                 //
5433                                 if (getter == null)
5434                                         return null;
5435
5436                                 if (ec.CurrentBlock.Toplevel.GetTransparentIdentifier (PropertyInfo.Name) != null) {
5437                                         Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
5438                                                 PropertyInfo.Name);
5439                                 } else {
5440                                         Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
5441                                                 GetSignatureForError ());
5442                                 }
5443                                 return null;
5444                         }
5445
5446                         if (TypeManager.GetParameterData (setter).Count != 1){
5447                                 Error_PropertyNotFound (setter, false);
5448                                 return null;
5449                         }
5450
5451                         bool must_do_cs1540_check;
5452                         if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
5453                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
5454                                 if (pm != null && pm.HasCustomAccessModifier) {
5455                                         Report.SymbolRelatedToPreviousError (pm);
5456                                         Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
5457                                                 TypeManager.CSharpSignature (setter));
5458                                 }
5459                                 else {
5460                                         Report.SymbolRelatedToPreviousError (setter);
5461                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
5462                                 }
5463                                 return null;
5464                         }
5465                         
5466                         if (!InstanceResolve (ec, PropertyInfo.DeclaringType.IsValueType, must_do_cs1540_check))
5467                                 return null;
5468                         
5469                         //
5470                         // Only base will allow this invocation to happen.
5471                         //
5472                         if (IsBase && setter.IsAbstract){
5473                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
5474                                 return null;
5475                         }
5476
5477                         return this;
5478                 }
5479                 
5480                 public override void Emit (EmitContext ec)
5481                 {
5482                         Emit (ec, false);
5483                 }
5484                 
5485                 public void Emit (EmitContext ec, bool leave_copy)
5486                 {
5487                         //
5488                         // Special case: length of single dimension array property is turned into ldlen
5489                         //
5490                         if (IsSingleDimensionalArrayLength ()) {
5491                                 if (!prepared)
5492                                         EmitInstance (ec, false);
5493                                 ec.ig.Emit (OpCodes.Ldlen);
5494                                 ec.ig.Emit (OpCodes.Conv_I4);
5495                                 return;
5496                         }
5497
5498                         Invocation.EmitCall (ec, IsBase, InstanceExpression, getter, null, loc, prepared, false);
5499                         
5500                         if (leave_copy) {
5501                                 ec.ig.Emit (OpCodes.Dup);
5502                                 if (!is_static) {
5503                                         temp = new LocalTemporary (this.Type);
5504                                         temp.Store (ec);
5505                                 }
5506                         }
5507                 }
5508
5509                 //
5510                 // Implements the IAssignMethod interface for assignments
5511                 //
5512                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5513                 {
5514                         Expression my_source = source;
5515
5516                         if (prepare_for_load) {
5517                                 prepared = true;
5518                                 source.Emit (ec);
5519                                 
5520                                 if (leave_copy) {
5521                                         ec.ig.Emit (OpCodes.Dup);
5522                                         if (!is_static) {
5523                                                 temp = new LocalTemporary (this.Type);
5524                                                 temp.Store (ec);
5525                                         }
5526                                 }
5527                         } else if (leave_copy) {
5528                                 source.Emit (ec);
5529                                 temp = new LocalTemporary (this.Type);
5530                                 temp.Store (ec);
5531                                 my_source = temp;
5532                         }
5533
5534                         ArrayList args = new ArrayList (1);
5535                         args.Add (new Argument (my_source, Argument.AType.Expression));
5536                         
5537                         Invocation.EmitCall (ec, IsBase, InstanceExpression, setter, args, loc, false, prepared);
5538                         
5539                         if (temp != null) {
5540                                 temp.Emit (ec);
5541                                 temp.Release (ec);
5542                         }
5543                 }
5544         }
5545
5546         /// <summary>
5547         ///   Fully resolved expression that evaluates to an Event
5548         /// </summary>
5549         public class EventExpr : MemberExpr {
5550                 public readonly EventInfo EventInfo;
5551
5552                 bool is_static;
5553                 MethodInfo add_accessor, remove_accessor;
5554
5555                 public EventExpr (EventInfo ei, Location loc)
5556                 {
5557                         EventInfo = ei;
5558                         this.loc = loc;
5559                         eclass = ExprClass.EventAccess;
5560
5561                         add_accessor = TypeManager.GetAddMethod (ei);
5562                         remove_accessor = TypeManager.GetRemoveMethod (ei);
5563                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
5564                                 is_static = true;
5565
5566                         if (EventInfo is MyEventBuilder){
5567                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
5568                                 type = eb.EventType;
5569                                 eb.SetUsed ();
5570                         } else
5571                                 type = EventInfo.EventHandlerType;
5572                 }
5573
5574                 public override string Name {
5575                         get {
5576                                 return EventInfo.Name;
5577                         }
5578                 }
5579
5580                 public override bool IsInstance {
5581                         get {
5582                                 return !is_static;
5583                         }
5584                 }
5585
5586                 public override bool IsStatic {
5587                         get {
5588                                 return is_static;
5589                         }
5590                 }
5591
5592                 public override Type DeclaringType {
5593                         get {
5594                                 return EventInfo.DeclaringType;
5595                         }
5596                 }
5597                 
5598                 void Error_AssignmentEventOnly ()
5599                 {
5600                         Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
5601                                 GetSignatureForError ());
5602                 }
5603
5604                 public override MemberExpr ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
5605                                                                 SimpleName original)
5606                 {
5607                         //
5608                         // If the event is local to this class, we transform ourselves into a FieldExpr
5609                         //
5610
5611                         if (EventInfo.DeclaringType == ec.ContainerType ||
5612                             TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
5613                                 EventField mi = TypeManager.GetEventField (EventInfo);
5614
5615                                 if (mi != null) {
5616                                         if (!ec.IsInObsoleteScope)
5617                                                 mi.CheckObsoleteness (loc);
5618
5619                                         if ((mi.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0 && !ec.IsInCompoundAssignment)
5620                                                 Error_AssignmentEventOnly ();
5621                                         
5622                                         FieldExpr ml = new FieldExpr (mi.FieldBuilder, loc);
5623
5624                                         InstanceExpression = null;
5625                                 
5626                                         return ml.ResolveMemberAccess (ec, left, loc, original);
5627                                 }
5628                         }
5629                         
5630                         if (left is This && !ec.IsInCompoundAssignment)                 
5631                                 Error_AssignmentEventOnly ();
5632
5633                         return base.ResolveMemberAccess (ec, left, loc, original);
5634                 }
5635
5636                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
5637                 {
5638                         if (is_static) {
5639                                 InstanceExpression = null;
5640                                 return true;
5641                         }
5642
5643                         if (InstanceExpression == null) {
5644                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5645                                 return false;
5646                         }
5647
5648                         InstanceExpression = InstanceExpression.DoResolve (ec);
5649                         if (InstanceExpression == null)
5650                                 return false;
5651
5652                         if (IsBase && add_accessor.IsAbstract) {
5653                                 Error_CannotCallAbstractBase(TypeManager.CSharpSignature(add_accessor));
5654                                 return false;
5655                         }
5656
5657                         //
5658                         // This is using the same mechanism as the CS1540 check in PropertyExpr.
5659                         // However, in the Event case, we reported a CS0122 instead.
5660                         //
5661                         if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
5662                             InstanceExpression.Type != ec.ContainerType &&
5663                             TypeManager.IsSubclassOf (ec.ContainerType, InstanceExpression.Type)) {
5664                                 Report.SymbolRelatedToPreviousError (EventInfo);
5665                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
5666                                 return false;
5667                         }
5668
5669                         return true;
5670                 }
5671
5672                 public bool IsAccessibleFrom (Type invocation_type)
5673                 {
5674                         bool dummy;
5675                         return IsAccessorAccessible (invocation_type, add_accessor, out dummy) &&
5676                                 IsAccessorAccessible (invocation_type, remove_accessor, out dummy);
5677                 }
5678
5679                 public override Expression CreateExpressionTree (EmitContext ec)
5680                 {
5681                         throw new NotSupportedException ("ET");
5682                 }
5683
5684                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5685                 {
5686                         // contexts where an LValue is valid have already devolved to FieldExprs
5687                         Error_CannotAssign ();
5688                         return null;
5689                 }
5690
5691                 public override Expression DoResolve (EmitContext ec)
5692                 {
5693                         bool must_do_cs1540_check;
5694                         if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
5695                               IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
5696                                 Report.SymbolRelatedToPreviousError (EventInfo);
5697                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
5698                                 return null;
5699                         }
5700
5701                         if (!InstanceResolve (ec, must_do_cs1540_check))
5702                                 return null;
5703
5704                         if (!ec.IsInCompoundAssignment) {
5705                                 Error_CannotAssign ();
5706                                 return null;
5707                         }
5708                         
5709                         return this;
5710                 }               
5711
5712                 public override void Emit (EmitContext ec)
5713                 {
5714                         Error_CannotAssign ();
5715                 }
5716
5717                 public void Error_CannotAssign ()
5718                 {
5719                         Report.Error (70, loc,
5720                                 "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
5721                                 GetSignatureForError (), TypeManager.CSharpName (EventInfo.DeclaringType));
5722                 }
5723
5724                 public override string GetSignatureForError ()
5725                 {
5726                         return TypeManager.CSharpSignature (EventInfo);
5727                 }
5728
5729                 public void EmitAddOrRemove (EmitContext ec, bool is_add, Expression source)
5730                 {
5731                         ArrayList args = new ArrayList (1);
5732                         args.Add (new Argument (source, Argument.AType.Expression));
5733                         Invocation.EmitCall (ec, IsBase, InstanceExpression, is_add ? add_accessor : remove_accessor, args, loc);
5734                 }
5735         }
5736
5737         public class TemporaryVariable : VariableReference
5738         {
5739                 LocalInfo li;
5740
5741                 public TemporaryVariable (Type type, Location loc)
5742                 {
5743                         this.type = type;
5744                         this.loc = loc;
5745                         eclass = ExprClass.Variable;
5746                 }
5747
5748                 public override Expression CreateExpressionTree (EmitContext ec)
5749                 {
5750                         throw new NotSupportedException ("ET");
5751                 }
5752
5753                 public override Expression DoResolve (EmitContext ec)
5754                 {
5755                         if (li != null)
5756                                 return this;
5757
5758                         TypeExpr te = new TypeExpression (type, loc);
5759                         li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
5760                         if (!li.Resolve (ec))
5761                                 return null;
5762
5763                         if (ec.MustCaptureVariable (li) && ec.IsVariableCapturingRequired) {
5764                                 AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
5765                                 storey.CaptureLocalVariable (ec, li);
5766                         }
5767
5768                         return this;
5769                 }
5770                 
5771                 public override void Emit (EmitContext ec)
5772                 {
5773                         Emit (ec, false);
5774                 }
5775
5776                 public void EmitAssign (EmitContext ec, Expression source)
5777                 {
5778                         EmitAssign (ec, source, false, false);
5779                 }
5780
5781                 public override HoistedVariable HoistedVariable {
5782                         get { return li.HoistedVariableReference; }
5783                 }
5784
5785                 public override bool IsFixed {
5786                         get { return true; }
5787                 }
5788
5789                 public override bool IsRef {
5790                         get { return false; }
5791                 }
5792
5793                 protected override ILocalVariable Variable {
5794                         get { return li; }
5795                 }
5796
5797                 public override VariableInfo VariableInfo {
5798                         get { throw new NotImplementedException (); }
5799                 }
5800         }
5801
5802         /// 
5803         /// Handles `var' contextual keyword; var becomes a keyword only
5804         /// if no type called var exists in a variable scope
5805         /// 
5806         public class VarExpr : SimpleName
5807         {
5808                 // Used for error reporting only
5809                 ArrayList initializer;
5810
5811                 public VarExpr (Location loc)
5812                         : base ("var", loc)
5813                 {
5814                 }
5815
5816                 public ArrayList VariableInitializer {
5817                         set {
5818                                 this.initializer = value;
5819                         }
5820                 }
5821
5822                 public bool InferType (EmitContext ec, Expression right_side)
5823                 {
5824                         if (type != null)
5825                                 throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
5826                         
5827                         type = right_side.Type;
5828                         if (type == TypeManager.null_type || type == TypeManager.void_type || type == TypeManager.anonymous_method_type) {
5829                                 Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
5830                                               right_side.GetSignatureForError ());
5831                                 return false;
5832                         }
5833
5834                         eclass = ExprClass.Variable;
5835                         return true;
5836                 }
5837
5838                 protected override void Error_TypeOrNamespaceNotFound (IResolveContext ec)
5839                 {
5840                         Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
5841                 }
5842
5843                 public override TypeExpr ResolveAsContextualType (IResolveContext rc, bool silent)
5844                 {
5845                         TypeExpr te = base.ResolveAsContextualType (rc, true);
5846                         if (te != null)
5847                                 return te;
5848
5849                         if (initializer == null)
5850                                 return null;
5851                         
5852                         if (initializer.Count > 1) {
5853                                 Location loc = ((Mono.CSharp.CSharpParser.VariableDeclaration)initializer [1]).Location;
5854                                 Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
5855                                 initializer = null;
5856                                 return null;
5857                         }
5858                                 
5859                         Expression variable_initializer = ((Mono.CSharp.CSharpParser.VariableDeclaration)initializer [0]).expression_or_array_initializer;
5860                         if (variable_initializer == null) {
5861                                 Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
5862                                 return null;
5863                         }
5864                         
5865                         return null;
5866                 }
5867         }
5868 }