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