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