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