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