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