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