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