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