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