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