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