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