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