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