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