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