Remove TypeBuilder from DefineType
[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.type.IsAccessible (ec.CurrentType)) {
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, Constructor.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                 protected static 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                 protected abstract TypeExpr DoResolveAsTypeStep (IMemberContext ec);
2502
2503                 public override bool Equals (object obj)
2504                 {
2505                         TypeExpr tobj = obj as TypeExpr;
2506                         if (tobj == null)
2507                                 return false;
2508
2509                         return Type == tobj.Type;
2510                 }
2511
2512                 public override int GetHashCode ()
2513                 {
2514                         return Type.GetHashCode ();
2515                 }
2516         }
2517
2518         /// <summary>
2519         ///   Fully resolved Expression that already evaluated to a type
2520         /// </summary>
2521         public class TypeExpression : TypeExpr {
2522                 public TypeExpression (TypeSpec t, Location l)
2523                 {
2524                         Type = t;
2525                         eclass = ExprClass.Type;
2526                         loc = l;
2527                 }
2528
2529                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
2530                 {
2531                         return this;
2532                 }
2533
2534                 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
2535                 {
2536                         return this;
2537                 }
2538         }
2539
2540         /// <summary>
2541         ///   This class denotes an expression which evaluates to a member
2542         ///   of a struct or a class.
2543         /// </summary>
2544         public abstract class MemberExpr : Expression
2545         {
2546                 //
2547                 // An instance expression associated with this member, if it's a
2548                 // non-static member
2549                 //
2550                 public Expression InstanceExpression;
2551
2552                 /// <summary>
2553                 ///   The name of this member.
2554                 /// </summary>
2555                 public abstract string Name {
2556                         get;
2557                 }
2558
2559                 //
2560                 // When base.member is used
2561                 //
2562                 public bool IsBase {
2563                         get { return InstanceExpression is BaseThis; }
2564                 }
2565
2566                 /// <summary>
2567                 ///   Whether this is an instance member.
2568                 /// </summary>
2569                 public abstract bool IsInstance {
2570                         get;
2571                 }
2572
2573                 /// <summary>
2574                 ///   Whether this is a static member.
2575                 /// </summary>
2576                 public abstract bool IsStatic {
2577                         get;
2578                 }
2579
2580                 // TODO: Not needed
2581                 protected abstract TypeSpec DeclaringType {
2582                         get;
2583                 }
2584
2585                 //
2586                 // Converts best base candidate for virtual method starting from QueriedBaseType
2587                 //
2588                 protected MethodSpec CandidateToBaseOverride (ResolveContext rc, MethodSpec method)
2589                 {
2590                         //
2591                         // Only when base.member is used and method is virtual
2592                         //
2593                         if (!IsBase)
2594                                 return method;
2595
2596                         //
2597                         // Overload resulution works on virtual or non-virtual members only (no overrides). That
2598                         // means for base.member access we have to find the closest match after we found best candidate
2599                         //
2600                         if ((method.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.STATIC)) != Modifiers.STATIC) {
2601                                 //
2602                                 // The method could already be what we are looking for
2603                                 //
2604                                 TypeSpec[] targs = null;
2605                                 if (method.DeclaringType != InstanceExpression.Type) {
2606                                         var base_override = MemberCache.FindMember (InstanceExpression.Type, new MemberFilter (method), BindingRestriction.InstanceOnly) as MethodSpec;
2607                                         if (base_override != null && base_override.DeclaringType != method.DeclaringType) {
2608                                                 if (base_override.IsGeneric)
2609                                                         targs = method.TypeArguments;
2610
2611                                                 method = base_override;
2612                                         }
2613                                 }
2614
2615                                 // TODO: For now we do it for any hoisted call even if it's needed for
2616                                 // hoisted stories only but that requires a new expression wrapper
2617                                 if (rc.CurrentAnonymousMethod != null) {
2618                                         if (targs == null && method.IsGeneric) {
2619                                                 targs = method.TypeArguments;
2620                                                 method = method.GetGenericMethodDefinition ();
2621                                         }
2622
2623                                         if (method.Parameters.HasArglist)
2624                                                 throw new NotImplementedException ("__arglist base call proxy");
2625
2626                                         method = rc.CurrentMemberDefinition.Parent.PartialContainer.CreateHoistedBaseCallProxy (rc, method);
2627
2628                                         // Ideally this should apply to any proxy rewrite but in the case of unary mutators on
2629                                         // get/set member expressions second call would fail to proxy because left expression
2630                                         // would be of 'this' and not 'base'
2631                                         if (rc.CurrentType.IsStruct)
2632                                                 InstanceExpression = new This (loc).Resolve (rc);
2633                                 }
2634
2635                                 if (targs != null)
2636                                         method = method.MakeGenericMethod (targs);
2637                         }
2638
2639                         //
2640                         // Only base will allow this invocation to happen.
2641                         //
2642                         if (method.IsAbstract) {
2643                                 Error_CannotCallAbstractBase (rc, method.GetSignatureForError ());
2644                         }
2645
2646                         return method;
2647                 }
2648
2649                 protected void CheckProtectedMemberAccess<T> (ResolveContext rc, T member) where T : MemberSpec
2650                 {
2651                         if (InstanceExpression == null)
2652                                 return;
2653
2654                         if ((member.Modifiers & Modifiers.AccessibilityMask) == Modifiers.PROTECTED && !(InstanceExpression is This)) {
2655                                 var ct = rc.CurrentType;
2656                                 var expr_type = InstanceExpression.Type;
2657                                 if (ct != expr_type) {
2658                                         expr_type = expr_type.GetDefinition ();
2659                                         if (ct != expr_type && !IsSameOrBaseQualifier (ct, expr_type)) {
2660                                                 rc.Report.SymbolRelatedToPreviousError (member);
2661                                                 rc.Report.Error (1540, loc,
2662                                                         "Cannot access protected member `{0}' via a qualifier of type `{1}'. The qualifier must be of type `{2}' or derived from it",
2663                                                         member.GetSignatureForError (), expr_type.GetSignatureForError (), ct.GetSignatureForError ());
2664                                         }
2665                                 }
2666                         }
2667                 }
2668
2669                 static bool IsSameOrBaseQualifier (TypeSpec type, TypeSpec qtype)
2670                 {
2671                         do {
2672                                 type = type.GetDefinition ();
2673
2674                                 if (type == qtype || TypeManager.IsFamilyAccessible (qtype, type))
2675                                         return true;
2676
2677                                 type = type.DeclaringType;
2678                         } while (type != null);
2679
2680                         return false;
2681                 }
2682
2683                 protected void DoBestMemberChecks<T> (ResolveContext rc, T member) where T : MemberSpec, IInterfaceMemberSpec
2684                 {
2685                         if (InstanceExpression != null) {
2686                                 InstanceExpression = InstanceExpression.Resolve (rc);
2687                                 CheckProtectedMemberAccess (rc, member);
2688                         }
2689
2690                         if (member.MemberType.IsPointer && !rc.IsUnsafe) {
2691                                 UnsafeError (rc, loc);
2692                         }
2693
2694                         if (!rc.IsObsolete) {
2695                                 ObsoleteAttribute oa = member.GetAttributeObsolete ();
2696                                 if (oa != null)
2697                                         AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report);
2698                         }
2699
2700                         if (!(member is FieldSpec))
2701                                 member.MemberDefinition.SetIsUsed ();
2702                 }
2703
2704                 protected virtual void Error_CannotCallAbstractBase (ResolveContext rc, string name)
2705                 {
2706                         rc.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
2707                 }
2708
2709                 //
2710                 // Implements identicial simple name and type-name
2711                 //
2712                 public Expression ProbeIdenticalTypeName (ResolveContext rc, Expression left, SimpleName name)
2713                 {
2714                         var t = left.Type;
2715                         if (t.Kind == MemberKind.InternalCompilerType || t is ElementTypeSpec || t.Arity > 0)
2716                                 return left;
2717
2718                         // 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
2719                         // a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name
2720
2721                         if (left is MemberExpr || left is VariableReference) {
2722                                 rc.Report.DisableReporting ();
2723                                 Expression identical_type = rc.LookupNamespaceOrType (name.Name, 0, loc, true) as TypeExpr;
2724                                 rc.Report.EnableReporting ();
2725                                 if (identical_type != null && identical_type.Type == left.Type)
2726                                         return identical_type;
2727                         }
2728
2729                         return left;
2730                 }
2731
2732                 public bool ResolveInstanceExpression (ResolveContext rc, Expression rhs)
2733                 {
2734                         if (IsStatic) {
2735                                 if (InstanceExpression != null) {
2736                                         if (InstanceExpression is TypeExpr) {
2737                                                 ObsoleteAttribute oa = InstanceExpression.Type.GetAttributeObsolete ();
2738                                                 if (oa != null && !rc.IsObsolete) {
2739                                                         AttributeTester.Report_ObsoleteMessage (oa, InstanceExpression.GetSignatureForError (), loc, rc.Report);
2740                                                 }
2741                                         } else {
2742                                                 var runtime_expr = InstanceExpression as RuntimeValueExpression;
2743                                                 if (runtime_expr == null || !runtime_expr.IsSuggestionOnly) {
2744                                                         rc.Report.Error (176, loc,
2745                                                                 "Static member `{0}' cannot be accessed with an instance reference, qualify it with a type name instead",
2746                                                                 GetSignatureForError ());
2747                                                 }
2748                                         }
2749
2750                                         InstanceExpression = null;
2751                                 }
2752
2753                                 return false;
2754                         }
2755
2756                         if (InstanceExpression == null || InstanceExpression is TypeExpr) {
2757                                 if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) {
2758                                         if (rc.HasSet (ResolveContext.Options.FieldInitializerScope))
2759                                                 rc.Report.Error (236, loc,
2760                                                         "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2761                                                         GetSignatureForError ());
2762                                         else
2763                                                 rc.Report.Error (120, loc,
2764                                                         "An object reference is required to access non-static member `{0}'",
2765                                                         GetSignatureForError ());
2766
2767                                         return false;
2768                                 }
2769
2770                                 if (!TypeManager.IsFamilyAccessible (rc.CurrentType, DeclaringType)) {
2771                                         rc.Report.Error (38, loc,
2772                                                 "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2773                                                 DeclaringType.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
2774                                 }
2775
2776                                 InstanceExpression = new This (loc);
2777                                 if (this is FieldExpr && rc.CurrentType.IsStruct) {
2778                                         using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
2779                                                 InstanceExpression = InstanceExpression.Resolve (rc);
2780                                         }
2781                                 } else {
2782                                         InstanceExpression = InstanceExpression.Resolve (rc);
2783                                 }
2784
2785                                 return false;
2786                         }
2787
2788                         var me = InstanceExpression as MemberExpr;
2789                         if (me != null) {
2790                                 me.ResolveInstanceExpression (rc, rhs);
2791
2792                                 var fe = me as FieldExpr;
2793                                 if (fe != null && fe.IsMarshalByRefAccess ()) {
2794                                         rc.Report.SymbolRelatedToPreviousError (me.DeclaringType);
2795                                         rc.Report.Warning (1690, 1, loc,
2796                                                 "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
2797                                                 me.GetSignatureForError ());
2798                                 }
2799
2800                                 return true;
2801                         }
2802
2803                         //
2804                         // Run member-access postponed check once we know that
2805                         // the expression is not field expression which is the only
2806                         // expression which can use uninitialized this
2807                         //
2808                         if (InstanceExpression is This && !(this is FieldExpr) && rc.CurrentType.IsStruct) {
2809                                 ((This)InstanceExpression).CheckStructThisDefiniteAssignment (rc);
2810                         }
2811
2812                         //
2813                         // Additional checks for l-value member access
2814                         //
2815                         if (rhs != null) {
2816                                 //
2817                                 // TODO: It should be recursive but that would break csc compatibility
2818                                 //
2819                                 if (InstanceExpression is UnboxCast) {
2820                                         rc.Report.Error (445, InstanceExpression.Location, "Cannot modify the result of an unboxing conversion");
2821                                 }
2822                         }
2823
2824                         return true;
2825                 }
2826
2827                 public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
2828                 {
2829                         if (left != null && left.IsNull && TypeManager.IsReferenceType (left.Type)) {
2830                                 ec.Report.Warning (1720, 1, left.Location,
2831                                         "Expression will always cause a `{0}'", "System.NullReferenceException");
2832                         }
2833
2834                         InstanceExpression = left;
2835                         return this;
2836                 }
2837
2838                 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2839                 {
2840                         TypeSpec instance_type = InstanceExpression.Type;
2841                         if (TypeManager.IsValueType (instance_type)) {
2842                                 if (InstanceExpression is IMemoryLocation) {
2843                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2844                                 } else {
2845                                         LocalTemporary t = new LocalTemporary (instance_type);
2846                                         InstanceExpression.Emit (ec);
2847                                         t.Store (ec);
2848                                         t.AddressOf (ec, AddressOp.Store);
2849                                 }
2850                         } else {
2851                                 InstanceExpression.Emit (ec);
2852
2853                                 // Only to make verifier happy
2854                                 if (instance_type.IsGenericParameter && !(InstanceExpression is This) && TypeManager.IsReferenceType (instance_type))
2855                                         ec.Emit (OpCodes.Box, instance_type);
2856                         }
2857
2858                         if (prepare_for_load)
2859                                 ec.Emit (OpCodes.Dup);
2860                 }
2861
2862                 public abstract void SetTypeArguments (ResolveContext ec, TypeArguments ta);
2863         }
2864
2865         // 
2866         // Represents a group of extension method candidates for whole namespace
2867         // 
2868         class ExtensionMethodGroupExpr : MethodGroupExpr, OverloadResolver.IErrorHandler
2869         {
2870                 NamespaceEntry namespace_entry;
2871                 public readonly Expression ExtensionExpression;
2872
2873                 public ExtensionMethodGroupExpr (IList<MethodSpec> list, NamespaceEntry n, Expression extensionExpr, Location l)
2874                         : base (list.Cast<MemberSpec>().ToList (), extensionExpr.Type, l)
2875                 {
2876                         this.namespace_entry = n;
2877                         this.ExtensionExpression = extensionExpr;
2878                 }
2879
2880                 public override bool IsStatic {
2881                         get { return true; }
2882                 }
2883
2884                 public override IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
2885                 {
2886                         if (namespace_entry == null)
2887                                 return null;
2888
2889                         //
2890                         // For extension methodgroup we are not looking for base members but parent
2891                         // namespace extension methods
2892                         //
2893                         int arity = type_arguments == null ? 0 : type_arguments.Count;
2894                         var found = namespace_entry.LookupExtensionMethod (DeclaringType, Name, arity, ref namespace_entry);
2895                         if (found == null)
2896                                 return null;
2897
2898                         return found.Cast<MemberSpec> ().ToList ();
2899                 }
2900
2901                 public override MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
2902                 {
2903                         // We are already here
2904                         return null;
2905                 }
2906
2907                 public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, OverloadResolver.IErrorHandler ehandler, OverloadResolver.Restrictions restr)
2908                 {
2909                         if (arguments == null)
2910                                 arguments = new Arguments (1);
2911
2912                         arguments.Insert (0, new Argument (ExtensionExpression, Argument.AType.ExtensionType));
2913                         var res = base.OverloadResolve (ec, ref arguments, ehandler ?? this, restr);
2914
2915                         // Store resolved argument and restore original arguments
2916                         if (res == null) {
2917                                 // Clean-up modified arguments for error reporting
2918                                 arguments.RemoveAt (0);
2919                                 return null;
2920                         }
2921
2922                         var me = ExtensionExpression as MemberExpr;
2923                         if (me != null)
2924                                 me.ResolveInstanceExpression (ec, null);
2925
2926                         InstanceExpression = null;
2927                         return this;
2928                 }
2929
2930                 #region IErrorHandler Members
2931
2932                 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous)
2933                 {
2934                         return false;
2935                 }
2936
2937                 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
2938                 {
2939                         rc.Report.SymbolRelatedToPreviousError (best);
2940                         rc.Report.Error (1928, loc,
2941                                 "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
2942                                 queried_type.GetSignatureForError (), Name, best.GetSignatureForError ());
2943
2944                         if (index == 0) {
2945                                 rc.Report.Error (1929, loc,
2946                                         "Extension method instance type `{0}' cannot be converted to `{1}'",
2947                                         arg.Type.GetSignatureForError (), ((MethodSpec)best).Parameters.ExtensionMethodType.GetSignatureForError ());
2948                         }
2949
2950                         return true;
2951                 }
2952
2953                 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
2954                 {
2955                         return false;
2956                 }
2957
2958                 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
2959                 {
2960                         return false;
2961                 }
2962
2963                 #endregion
2964         }
2965
2966         /// <summary>
2967         ///   MethodGroupExpr represents a group of method candidates which
2968         ///   can be resolved to the best method overload
2969         /// </summary>
2970         public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider
2971         {
2972                 protected IList<MemberSpec> Methods;
2973                 MethodSpec best_candidate;
2974                 TypeSpec best_candidate_return;
2975                 protected TypeArguments type_arguments;
2976
2977                 SimpleName simple_name;
2978                 protected TypeSpec queried_type;
2979
2980                 public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location loc)
2981                 {
2982                         Methods = mi;
2983                         this.loc = loc;
2984                         this.type = InternalType.MethodGroup;
2985
2986                         eclass = ExprClass.MethodGroup;
2987                         queried_type = type;
2988                 }
2989
2990                 public MethodGroupExpr (MethodSpec m, TypeSpec type, Location loc)
2991                         : this (new MemberSpec[] { m }, type, loc)
2992                 {
2993                 }
2994
2995                 #region Properties
2996
2997                 public MethodSpec BestCandidate {
2998                         get {
2999                                 return best_candidate;
3000                         }
3001                 }
3002
3003                 public TypeSpec BestCandidateReturnType {
3004                         get {
3005                                 return best_candidate_return;
3006                         }
3007                 }
3008
3009                 protected override TypeSpec DeclaringType {
3010                         get {
3011                                 return queried_type;
3012                         }
3013                 }
3014
3015                 public override bool IsInstance {
3016                         get {
3017                                 if (best_candidate != null)
3018                                         return !best_candidate.IsStatic;
3019
3020                                 return false;
3021                         }
3022                 }
3023
3024                 public override bool IsStatic {
3025                         get {
3026                                 if (best_candidate != null)
3027                                         return best_candidate.IsStatic;
3028
3029                                 return false;
3030                         }
3031                 }
3032
3033                 public override string Name {
3034                         get {
3035                                 if (best_candidate != null)
3036                                         return best_candidate.Name;
3037
3038                                 // TODO: throw ?
3039                                 return Methods.First ().Name;
3040                         }
3041                 }
3042
3043                 #endregion
3044
3045                 //
3046                 // When best candidate is already know this factory can be used
3047                 // to avoid expensive overload resolution to be called
3048                 //
3049                 // NOTE: InstanceExpression has to be set manually
3050                 //
3051                 public static MethodGroupExpr CreatePredefined (MethodSpec best, TypeSpec queriedType, Location loc)
3052                 {
3053                         return new MethodGroupExpr (best, queriedType, loc) {
3054                                 best_candidate = best,
3055                                 best_candidate_return = best.ReturnType
3056                         };
3057                 }
3058
3059                 public override string GetSignatureForError ()
3060                 {
3061                         if (best_candidate != null)
3062                                 return best_candidate.GetSignatureForError ();
3063
3064                         return Methods.First ().GetSignatureForError ();
3065                 }
3066
3067                 public override Expression CreateExpressionTree (ResolveContext ec)
3068                 {
3069                         if (best_candidate == null) {
3070                                 ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
3071                                 return null;
3072                         }
3073
3074                         if (best_candidate.IsConditionallyExcluded (loc))
3075                                 ec.Report.Error (765, loc,
3076                                         "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
3077                         
3078                         return new TypeOfMethod (best_candidate, loc);
3079                 }
3080                 
3081                 protected override Expression DoResolve (ResolveContext ec)
3082                 {
3083                         this.eclass = ExprClass.MethodGroup;
3084
3085                         if (InstanceExpression != null) {
3086                                 InstanceExpression = InstanceExpression.Resolve (ec);
3087                                 if (InstanceExpression == null)
3088                                         return null;
3089                         }
3090
3091                         return this;
3092                 }
3093
3094                 public override void Emit (EmitContext ec)
3095                 {
3096                         throw new NotSupportedException ();
3097                 }
3098                 
3099                 public void EmitCall (EmitContext ec, Arguments arguments)
3100                 {
3101                         Invocation.EmitCall (ec, InstanceExpression, best_candidate, arguments, loc);                   
3102                 }
3103
3104                 public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
3105                 {
3106                         ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
3107                                 Name, TypeManager.CSharpName (target));
3108                 }
3109
3110                 public static bool IsExtensionMethodArgument (Expression expr)
3111                 {
3112                         //
3113                         // LAMESPEC: No details about which expressions are not allowed
3114                         //
3115                         return !(expr is TypeExpr) && !(expr is BaseThis);
3116                 }
3117
3118                 /// <summary>
3119                 ///   Find the Applicable Function Members (7.4.2.1)
3120                 ///
3121                 ///   me: Method Group expression with the members to select.
3122                 ///       it might contain constructors or methods (or anything
3123                 ///       that maps to a method).
3124                 ///
3125                 ///   Arguments: ArrayList containing resolved Argument objects.
3126                 ///
3127                 ///   loc: The location if we want an error to be reported, or a Null
3128                 ///        location for "probing" purposes.
3129                 ///
3130                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3131                 ///            that is the best match of me on Arguments.
3132                 ///
3133                 /// </summary>
3134                 public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments args, OverloadResolver.IErrorHandler cerrors, OverloadResolver.Restrictions restr)
3135                 {
3136                         // TODO: causes issues with probing mode, remove explicit Kind check
3137                         if (best_candidate != null && best_candidate.Kind == MemberKind.Destructor)
3138                                 return this;
3139
3140                         var r = new OverloadResolver (Methods, type_arguments, restr, loc);
3141                         if ((restr & OverloadResolver.Restrictions.NoBaseMembers) == 0) {
3142                                 r.BaseMembersProvider = this;
3143                         }
3144
3145                         if (cerrors != null)
3146                                 r.CustomErrors = cerrors;
3147
3148                         // TODO: When in probing mode do IsApplicable only and when called again do VerifyArguments for full error reporting
3149                         best_candidate = r.ResolveMember<MethodSpec> (ec, ref args);
3150                         if (best_candidate == null)
3151                                 return r.BestCandidateIsDynamic ? this : null;
3152
3153                         // Overload resolver had to create a new method group, all checks bellow have already been executed
3154                         if (r.BestCandidateNewMethodGroup != null)
3155                                 return r.BestCandidateNewMethodGroup;
3156
3157                         if (best_candidate.Kind == MemberKind.Method) {
3158                                 if (InstanceExpression != null) {
3159                                         if (best_candidate.IsExtensionMethod && args[0].Expr == InstanceExpression) {
3160                                                 InstanceExpression = null;
3161                                         } else {
3162                                                 if (best_candidate.IsStatic && simple_name != null) {
3163                                                         InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name);
3164                                                 }
3165
3166                                                 InstanceExpression.Resolve (ec);
3167                                         }
3168                                 }
3169
3170                                 ResolveInstanceExpression (ec, null);
3171                                 if (InstanceExpression != null)
3172                                         CheckProtectedMemberAccess (ec, best_candidate);
3173                         }
3174
3175                         var base_override = CandidateToBaseOverride (ec, best_candidate);
3176                         if (base_override == best_candidate) {
3177                                 best_candidate_return = r.BestCandidateReturnType;
3178                         } else {
3179                                 best_candidate = base_override;
3180                                 best_candidate_return = best_candidate.ReturnType;
3181                         }
3182
3183                         return this;
3184                 }
3185
3186                 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
3187                 {
3188                         simple_name = original;
3189                         return base.ResolveMemberAccess (ec, left, original);
3190                 }
3191
3192                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
3193                 {
3194                         type_arguments = ta;
3195                 }
3196
3197                 #region IBaseMembersProvider Members
3198
3199                 public virtual IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
3200                 {
3201                         return baseType == null ? null : MemberCache.FindMembers (baseType, Methods [0].Name, false);
3202                 }
3203
3204                 public IParametersMember GetOverrideMemberParameters (MemberSpec member)
3205                 {
3206                         if (queried_type == member.DeclaringType)
3207                                 return null;
3208
3209                         return MemberCache.FindMember (queried_type, new MemberFilter ((MethodSpec) member),
3210                                 BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
3211                 }
3212
3213                 //
3214                 // Extension methods lookup after ordinary methods candidates failed to apply
3215                 //
3216                 public virtual MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
3217                 {
3218                         if (InstanceExpression == null)
3219                                 return null;
3220
3221                         InstanceExpression = InstanceExpression.Resolve (rc);
3222                         if (!IsExtensionMethodArgument (InstanceExpression))
3223                                 return null;
3224
3225                         int arity = type_arguments == null ? 0 : type_arguments.Count;
3226                         NamespaceEntry methods_scope = null;
3227                         var methods = rc.LookupExtensionMethod (InstanceExpression.Type, Methods[0].Name, arity, ref methods_scope);
3228                         if (methods == null)
3229                                 return null;
3230
3231                         var emg = new ExtensionMethodGroupExpr (methods, methods_scope, InstanceExpression, loc);
3232                         emg.SetTypeArguments (rc, type_arguments);
3233                         return emg;
3234                 }
3235
3236                 #endregion
3237         }
3238
3239         public struct OverloadResolver
3240         {
3241                 [Flags]
3242                 public enum Restrictions
3243                 {
3244                         None = 0,
3245                         DelegateInvoke = 1,
3246                         ProbingOnly     = 1 << 1,
3247                         CovariantDelegate = 1 << 2,
3248                         NoBaseMembers = 1 << 3,
3249                         BaseMembersIncluded = 1 << 4
3250                 }
3251
3252                 public interface IBaseMembersProvider
3253                 {
3254                         IList<MemberSpec> GetBaseMembers (TypeSpec baseType);
3255                         IParametersMember GetOverrideMemberParameters (MemberSpec member);
3256                         MethodGroupExpr LookupExtensionMethod (ResolveContext rc);
3257                 }
3258
3259                 public interface IErrorHandler
3260                 {
3261                         bool AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous);
3262                         bool ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument a, int index);
3263                         bool NoArgumentMatch (ResolveContext rc, MemberSpec best);
3264                         bool TypeInferenceFailed (ResolveContext rc, MemberSpec best);
3265                 }
3266
3267                 sealed class NoBaseMembers : IBaseMembersProvider
3268                 {
3269                         public static readonly IBaseMembersProvider Instance = new NoBaseMembers ();
3270
3271                         public IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
3272                         {
3273                                 return null;
3274                         }
3275
3276                         public IParametersMember GetOverrideMemberParameters (MemberSpec member)
3277                         {
3278                                 return null;
3279                         }
3280
3281                         public MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
3282                         {
3283                                 return null;
3284                         }
3285                 }
3286
3287                 struct AmbiguousCandidate
3288                 {
3289                         public readonly MemberSpec Member;
3290                         public readonly bool Expanded;
3291                         public readonly AParametersCollection Parameters;
3292
3293                         public AmbiguousCandidate (MemberSpec member, AParametersCollection parameters, bool expanded)
3294                         {
3295                                 Member = member;
3296                                 Parameters = parameters;
3297                                 Expanded = expanded;
3298                         }
3299                 }
3300
3301                 Location loc;
3302                 IList<MemberSpec> members;
3303                 TypeArguments type_arguments;
3304                 IBaseMembersProvider base_provider;
3305                 IErrorHandler custom_errors;
3306                 Restrictions restrictions;
3307                 MethodGroupExpr best_candidate_extension_group;
3308                 TypeSpec best_candidate_return_type;
3309
3310                 SessionReportPrinter lambda_conv_msgs;
3311                 ReportPrinter prev_recorder;
3312
3313                 public OverloadResolver (IList<MemberSpec> members, Restrictions restrictions, Location loc)
3314                         : this (members, null, restrictions, loc)
3315                 {
3316                 }
3317
3318                 public OverloadResolver (IList<MemberSpec> members, TypeArguments targs, Restrictions restrictions, Location loc)
3319                         : this ()
3320                 {
3321                         if (members == null || members.Count == 0)
3322                                 throw new ArgumentException ("empty members set");
3323
3324                         this.members = members;
3325                         this.loc = loc;
3326                         type_arguments = targs;
3327                         this.restrictions = restrictions;
3328                         if (IsDelegateInvoke)
3329                                 this.restrictions |= Restrictions.NoBaseMembers;
3330
3331                         base_provider = NoBaseMembers.Instance;
3332                 }
3333
3334                 #region Properties
3335
3336                 public IBaseMembersProvider BaseMembersProvider {
3337                         get {
3338                                 return base_provider;
3339                         }
3340                         set {
3341                                 base_provider = value;
3342                         }
3343                 }
3344
3345                 public bool BestCandidateIsDynamic { get; set; }
3346
3347                 //
3348                 // Best candidate was found in newly created MethodGroupExpr, used by extension methods
3349                 //
3350                 public MethodGroupExpr BestCandidateNewMethodGroup {
3351                         get {
3352                                 return best_candidate_extension_group;
3353                         }
3354                 }
3355
3356                 //
3357                 // Return type can be different between best candidate and closest override
3358                 //
3359                 public TypeSpec BestCandidateReturnType {
3360                         get {
3361                                 return best_candidate_return_type;
3362                         }
3363                 }
3364
3365                 public IErrorHandler CustomErrors {
3366                         get {
3367                                 return custom_errors;
3368                         }
3369                         set {
3370                                 custom_errors = value;
3371                         }
3372                 }
3373
3374                 TypeSpec DelegateType {
3375                         get {
3376                                 if ((restrictions & Restrictions.DelegateInvoke) == 0)
3377                                         throw new InternalErrorException ("Not running in delegate mode", loc);
3378
3379                                 return members [0].DeclaringType;
3380                         }
3381                 }
3382
3383                 bool IsProbingOnly {
3384                         get {
3385                                 return (restrictions & Restrictions.ProbingOnly) != 0;
3386                         }
3387                 }
3388
3389                 bool IsDelegateInvoke {
3390                         get {
3391                                 return (restrictions & Restrictions.DelegateInvoke) != 0;
3392                         }
3393                 }
3394
3395                 #endregion
3396
3397                 //
3398                 //  7.4.3.3  Better conversion from expression
3399                 //  Returns :   1    if a->p is better,
3400                 //              2    if a->q is better,
3401                 //              0 if neither is better
3402                 //
3403                 static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q)
3404                 {
3405                         TypeSpec argument_type = a.Type;
3406                         if (argument_type == InternalType.AnonymousMethod && RootContext.Version > LanguageVersion.ISO_2) {
3407                                 //
3408                                 // Uwrap delegate from Expression<T>
3409                                 //
3410                                 if (p.GetDefinition () == TypeManager.expression_type) {
3411                                         p = TypeManager.GetTypeArguments (p)[0];
3412                                 }
3413                                 if (q.GetDefinition () == TypeManager.expression_type) {
3414                                         q = TypeManager.GetTypeArguments (q)[0];
3415                                 }
3416
3417                                 p = Delegate.GetInvokeMethod (ec.Compiler, p).ReturnType;
3418                                 q = Delegate.GetInvokeMethod (ec.Compiler, q).ReturnType;
3419                                 if (p == TypeManager.void_type && q != TypeManager.void_type)
3420                                         return 2;
3421                                 if (q == TypeManager.void_type && p != TypeManager.void_type)
3422                                         return 1;
3423                         } else {
3424                                 if (argument_type == p)
3425                                         return 1;
3426
3427                                 if (argument_type == q)
3428                                         return 2;
3429                         }
3430
3431                         return BetterTypeConversion (ec, p, q);
3432                 }
3433
3434                 //
3435                 // 7.4.3.4  Better conversion from type
3436                 //
3437                 public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q)
3438                 {
3439                         if (p == null || q == null)
3440                                 throw new InternalErrorException ("BetterTypeConversion got a null conversion");
3441
3442                         if (p == TypeManager.int32_type) {
3443                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3444                                         return 1;
3445                         } else if (p == TypeManager.int64_type) {
3446                                 if (q == TypeManager.uint64_type)
3447                                         return 1;
3448                         } else if (p == TypeManager.sbyte_type) {
3449                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3450                                         q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3451                                         return 1;
3452                         } else if (p == TypeManager.short_type) {
3453                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3454                                         q == TypeManager.uint64_type)
3455                                         return 1;
3456                         } else if (p == InternalType.Dynamic) {
3457                                 // Dynamic is never better
3458                                 return 2;
3459                         }
3460
3461                         if (q == TypeManager.int32_type) {
3462                                 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3463                                         return 2;
3464                         } if (q == TypeManager.int64_type) {
3465                                 if (p == TypeManager.uint64_type)
3466                                         return 2;
3467                         } else if (q == TypeManager.sbyte_type) {
3468                                 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
3469                                         p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3470                                         return 2;
3471                         } if (q == TypeManager.short_type) {
3472                                 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
3473                                         p == TypeManager.uint64_type)
3474                                         return 2;
3475                         } else if (q == InternalType.Dynamic) {
3476                                 // Dynamic is never better
3477                                 return 1;
3478                         }
3479
3480                         // FIXME: handle lifted operators
3481
3482                         // TODO: this is expensive
3483                         Expression p_tmp = new EmptyExpression (p);
3484                         Expression q_tmp = new EmptyExpression (q);
3485
3486                         bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
3487                         bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
3488
3489                         if (p_to_q && !q_to_p)
3490                                 return 1;
3491
3492                         if (q_to_p && !p_to_q)
3493                                 return 2;
3494
3495                         return 0;
3496                 }
3497
3498                 /// <summary>
3499                 ///   Determines "Better function" between candidate
3500                 ///   and the current best match
3501                 /// </summary>
3502                 /// <remarks>
3503                 ///    Returns a boolean indicating :
3504                 ///     false if candidate ain't better
3505                 ///     true  if candidate is better than the current best match
3506                 /// </remarks>
3507                 static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
3508                         MemberSpec best, AParametersCollection bparam, bool best_params)
3509                 {
3510                         AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters;
3511                         AParametersCollection best_pd = ((IParametersMember) best).Parameters;
3512
3513                         bool better_at_least_one = false;
3514                         bool same = true;
3515                         int args_count = args == null ? 0 : args.Count;
3516                         int j = 0;
3517                         Argument a = null;
3518                         TypeSpec ct, bt;
3519                         for (int c_idx = 0, b_idx = 0; j < args_count; ++j, ++c_idx, ++b_idx) {
3520                                 a = args[j];
3521
3522                                 // Default arguments are ignored for better decision
3523                                 if (a.IsDefaultArgument)
3524                                         break;
3525
3526                                 //
3527                                 // When comparing named argument the parameter type index has to be looked up
3528                                 // in original parameter set (override version for virtual members)
3529                                 //
3530                                 NamedArgument na = a as NamedArgument;
3531                                 if (na != null) {
3532                                         int idx = cparam.GetParameterIndexByName (na.Name);
3533                                         ct = candidate_pd.Types[idx];
3534                                         if (candidate_params && candidate_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
3535                                                 ct = TypeManager.GetElementType (ct);
3536
3537                                         idx = bparam.GetParameterIndexByName (na.Name);
3538                                         bt = best_pd.Types[idx];
3539                                         if (best_params && best_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
3540                                                 bt = TypeManager.GetElementType (bt);
3541                                 } else {
3542                                         ct = candidate_pd.Types[c_idx];
3543                                         bt = best_pd.Types[b_idx];
3544
3545                                         if (candidate_params && candidate_pd.FixedParameters[c_idx].ModFlags == Parameter.Modifier.PARAMS) {
3546                                                 ct = TypeManager.GetElementType (ct);
3547                                                 --c_idx;
3548                                         }
3549
3550                                         if (best_params && best_pd.FixedParameters[b_idx].ModFlags == Parameter.Modifier.PARAMS) {
3551                                                 bt = TypeManager.GetElementType (bt);
3552                                                 --b_idx;
3553                                         }
3554                                 }
3555
3556                                 if (TypeSpecComparer.IsEqual (ct, bt))
3557                                         continue;
3558
3559                                 same = false;
3560                                 int result = BetterExpressionConversion (ec, a, ct, bt);
3561
3562                                 // for each argument, the conversion to 'ct' should be no worse than 
3563                                 // the conversion to 'bt'.
3564                                 if (result == 2)
3565                                         return false;
3566
3567                                 // for at least one argument, the conversion to 'ct' should be better than 
3568                                 // the conversion to 'bt'.
3569                                 if (result != 0)
3570                                         better_at_least_one = true;
3571                         }
3572
3573                         if (better_at_least_one)
3574                                 return true;
3575
3576                         //
3577                         // This handles the case
3578                         //
3579                         //   Add (float f1, float f2, float f3);
3580                         //   Add (params decimal [] foo);
3581                         //
3582                         // The call Add (3, 4, 5) should be ambiguous.  Without this check, the
3583                         // first candidate would've chosen as better.
3584                         //
3585                         if (!same && !a.IsDefaultArgument)
3586                                 return false;
3587
3588                         //
3589                         // The two methods have equal non-optional parameter types, apply tie-breaking rules
3590                         //
3591
3592                         //
3593                         // This handles the following cases:
3594                         //
3595                         //  Foo (int i) is better than Foo (int i, long l = 0)
3596                         //  Foo (params int[] args) is better than Foo (int i = 0, params int[] args)
3597                         //
3598                         // Prefer non-optional version
3599                         //
3600                         // LAMESPEC: Specification claims this should be done at last but the opposite is true
3601                         //
3602                         if (candidate_params == best_params && candidate_pd.Count != best_pd.Count) {
3603                                 if (candidate_pd.Count >= best_pd.Count)
3604                                         return false;
3605
3606                                 if (j < candidate_pd.Count && candidate_pd.FixedParameters[j].HasDefaultValue)
3607                                         return false;
3608
3609                                 return true;
3610                         }
3611
3612                         //
3613                         // One is a non-generic method and second is a generic method, then non-generic is better
3614                         //
3615                         if (best.IsGeneric != candidate.IsGeneric)
3616                                 return best.IsGeneric;
3617
3618                         //
3619                         // This handles the following cases:
3620                         //
3621                         //   Trim () is better than Trim (params char[] chars)
3622                         //   Concat (string s1, string s2, string s3) is better than
3623                         //     Concat (string s1, params string [] srest)
3624                         //   Foo (int, params int [] rest) is better than Foo (params int [] rest)
3625                         //
3626                         // Prefer non-expanded version
3627                         //
3628                         if (candidate_params != best_params)
3629                                 return best_params;
3630
3631                         int candidate_param_count = candidate_pd.Count;
3632                         int best_param_count = best_pd.Count;
3633
3634                         if (candidate_param_count != best_param_count)
3635                                 // can only happen if (candidate_params && best_params)
3636                                 return candidate_param_count > best_param_count && best_pd.HasParams;
3637
3638                         //
3639                         // Both methods have the same number of parameters, and the parameters have equal types
3640                         // Pick the "more specific" signature using rules over original (non-inflated) types
3641                         //
3642                         var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters;
3643                         var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
3644
3645                         bool specific_at_least_once = false;
3646                         for (j = 0; j < candidate_param_count; ++j) {
3647                                 NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument;
3648                                 if (na != null) {
3649                                         ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)];
3650                                         bt = best_def_pd.Types[bparam.GetParameterIndexByName (na.Name)];
3651                                 } else {
3652                                         ct = candidate_def_pd.Types[j];
3653                                         bt = best_def_pd.Types[j];
3654                                 }
3655
3656                                 if (ct == bt)
3657                                         continue;
3658                                 TypeSpec specific = MoreSpecific (ct, bt);
3659                                 if (specific == bt)
3660                                         return false;
3661                                 if (specific == ct)
3662                                         specific_at_least_once = true;
3663                         }
3664
3665                         if (specific_at_least_once)
3666                                 return true;
3667
3668                         return false;
3669                 }
3670
3671                 public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc)
3672                 {
3673                         rc.Report.Error (1729, loc,
3674                                 "The type `{0}' does not contain a constructor that takes `{1}' arguments",
3675                                 type.GetSignatureForError (), argCount.ToString ());
3676                 }
3677
3678                 //
3679                 // Determines if the candidate method is applicable to the given set of arguments
3680                 // There could be two different set of parameters for same candidate where one
3681                 // is the closest override for default values and named arguments checks and second
3682                 // one being the virtual base for the parameter types and modifiers.
3683                 //
3684                 // A return value rates candidate method compatibility,
3685                 // 0 = the best, int.MaxValue = the worst
3686                 //
3687                 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)
3688                 {
3689                         var pd = pm.Parameters;
3690                         int param_count = pd.Count;
3691                         int optional_count = 0;
3692                         int score;
3693                         Arguments orig_args = arguments;
3694
3695                         if (arg_count != param_count) {
3696                                 for (int i = 0; i < pd.Count; ++i) {
3697                                         if (pd.FixedParameters[i].HasDefaultValue) {
3698                                                 optional_count = pd.Count - i;
3699                                                 break;
3700                                         }
3701                                 }
3702
3703                                 int args_gap = System.Math.Abs (arg_count - param_count);
3704                                 if (optional_count != 0) {
3705                                         if (args_gap > optional_count)
3706                                                 return int.MaxValue - 10000 + args_gap - optional_count;
3707
3708                                         // Readjust expected number when params used
3709                                         if (pd.HasParams) {
3710                                                 optional_count--;
3711                                                 if (arg_count < param_count)
3712                                                         param_count--;
3713                                         } else if (arg_count > param_count) {
3714                                                 return int.MaxValue - 10000 + args_gap;
3715                                         }
3716                                 } else if (arg_count != param_count) {
3717                                         if (!pd.HasParams)
3718                                                 return int.MaxValue - 10000 + args_gap;
3719                                         if (arg_count < param_count - 1)
3720                                                 return int.MaxValue - 10000 + args_gap;
3721                                 }
3722
3723                                 // Resize to fit optional arguments
3724                                 if (optional_count != 0) {
3725                                         if (arguments == null) {
3726                                                 arguments = new Arguments (optional_count);
3727                                         } else {
3728                                                 // Have to create a new container, so the next run can do same
3729                                                 var resized = new Arguments (param_count);
3730                                                 resized.AddRange (arguments);
3731                                                 arguments = resized;
3732                                         }
3733
3734                                         for (int i = arg_count; i < param_count; ++i)
3735                                                 arguments.Add (null);
3736                                 }
3737                         }
3738
3739                         if (arg_count > 0) {
3740                                 //
3741                                 // Shuffle named arguments to the right positions if there are any
3742                                 //
3743                                 if (arguments[arg_count - 1] is NamedArgument) {
3744                                         arg_count = arguments.Count;
3745
3746                                         for (int i = 0; i < arg_count; ++i) {
3747                                                 bool arg_moved = false;
3748                                                 while (true) {
3749                                                         NamedArgument na = arguments[i] as NamedArgument;
3750                                                         if (na == null)
3751                                                                 break;
3752
3753                                                         int index = pd.GetParameterIndexByName (na.Name);
3754
3755                                                         // Named parameter not found
3756                                                         if (index < 0)
3757                                                                 return (i + 1) * 3;
3758
3759                                                         // already reordered
3760                                                         if (index == i)
3761                                                                 break;
3762
3763                                                         Argument temp;
3764                                                         if (index >= param_count) {
3765                                                                 // When using parameters which should not be available to the user
3766                                                                 if ((pd.FixedParameters[index].ModFlags & Parameter.Modifier.PARAMS) == 0)
3767                                                                         break;
3768
3769                                                                 arguments.Add (null);
3770                                                                 ++arg_count;
3771                                                                 temp = null;
3772                                                         } else {
3773                                                                 temp = arguments[index];
3774
3775                                                                 // The slot has been taken by positional argument
3776                                                                 if (temp != null && !(temp is NamedArgument))
3777                                                                         break;
3778                                                         }
3779
3780                                                         if (!arg_moved) {
3781                                                                 arguments = arguments.MarkOrderedArgument (na);
3782                                                                 arg_moved = true;
3783                                                         }
3784
3785                                                         arguments[index] = arguments[i];
3786                                                         arguments[i] = temp;
3787
3788                                                         if (temp == null)
3789                                                                 break;
3790                                                 }
3791                                         }
3792                                 } else {
3793                                         arg_count = arguments.Count;
3794                                 }
3795                         } else if (arguments != null) {
3796                                 arg_count = arguments.Count;
3797                         }
3798
3799                         //
3800                         // 1. Handle generic method using type arguments when specified or type inference
3801                         //
3802                         var ms = candidate as MethodSpec;
3803                         if (ms != null && ms.IsGeneric) {
3804                                 // Setup constraint checker for probing only
3805                                 ConstraintChecker cc = new ConstraintChecker (null);
3806
3807                                 if (type_arguments != null) {
3808                                         var g_args_count = ms.Arity;
3809                                         if (g_args_count != type_arguments.Count)
3810                                                 return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
3811
3812                                         ms = ms.MakeGenericMethod (type_arguments.Arguments);
3813                                 } else {
3814                                         // TODO: It should not be here (we don't know yet whether any argument is lambda) but
3815                                         // for now it simplifies things. I should probably add a callback to ResolveContext
3816                                         if (lambda_conv_msgs == null) {
3817                                                 lambda_conv_msgs = new SessionReportPrinter ();
3818                                                 prev_recorder = ec.Report.SetPrinter (lambda_conv_msgs);
3819                                         }
3820
3821                                         var ti = new TypeInference (arguments);
3822                                         TypeSpec[] i_args = ti.InferMethodArguments (ec, ms);
3823                                         lambda_conv_msgs.EndSession ();
3824
3825                                         if (i_args == null)
3826                                                 return ti.InferenceScore - 20000;
3827
3828                                         if (i_args.Length != 0) {
3829                                                 ms = ms.MakeGenericMethod (i_args);
3830                                         }
3831
3832                                         cc.IgnoreInferredDynamic = true;
3833                                 }
3834
3835                                 //
3836                                 // Type arguments constraints have to match for the method to be applicable
3837                                 //
3838                                 if (!cc.CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc)) {
3839                                         candidate = ms;
3840                                         return int.MaxValue - 25000;
3841                                 }
3842
3843                                 //
3844                                 // We have a generic return type and at same time the method is override which
3845                                 // means we have to also inflate override return type in case the candidate is
3846                                 // best candidate and override return type is different to base return type.
3847                                 // 
3848                                 // virtual Foo<T, object> with override Foo<T, dynamic>
3849                                 //
3850                                 if (candidate != pm) {
3851                                         MethodSpec override_ms = (MethodSpec) pm;
3852                                         var inflator = new TypeParameterInflator (ms.DeclaringType, override_ms.GenericDefinition.TypeParameters, ms.TypeArguments);
3853                                         returnType = inflator.Inflate (returnType);
3854                                 } else {
3855                                         returnType = ms.ReturnType;
3856                                 }
3857
3858                                 candidate = ms;
3859
3860                         } else {
3861                                 if (type_arguments != null)
3862                                         return int.MaxValue - 15000;
3863                         }
3864
3865                         //
3866                         // 2. Each argument has to be implicitly convertible to method parameter
3867                         //
3868                         Parameter.Modifier p_mod = 0;
3869                         TypeSpec pt = null;
3870                         TypeSpec[] ptypes = ((IParametersMember) candidate).Parameters.Types;
3871
3872                         for (int i = 0; i < arg_count; i++) {
3873                                 Argument a = arguments[i];
3874                                 if (a == null) {
3875                                         if (!pd.FixedParameters[i].HasDefaultValue) {
3876                                                 arguments = orig_args;
3877                                                 return arg_count * 2 + 2;
3878                                         }
3879
3880                                         //
3881                                         // Get the default value expression, we can use the same expression
3882                                         // if the type matches
3883                                         //
3884                                         Expression e = pd.FixedParameters[i].DefaultValue;
3885                                         if (!(e is Constant) || e.Type.IsGenericOrParentIsGeneric) {
3886                                                 //
3887                                                 // LAMESPEC: No idea what the exact rules are for System.Reflection.Missing.Value instead of null
3888                                                 //
3889                                                 if (e == EmptyExpression.MissingValue && ptypes[i] == TypeManager.object_type || ptypes[i] == InternalType.Dynamic) {
3890                                                         e = new MemberAccess (new MemberAccess (new MemberAccess (
3891                                                                 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Reflection", loc), "Missing", loc), "Value", loc);
3892                                                 } else {
3893                                                         e = new DefaultValueExpression (new TypeExpression (ptypes [i], loc), loc);
3894                                                 }
3895
3896                                                 e = e.Resolve (ec);
3897                                         }
3898
3899                                         arguments[i] = new Argument (e, Argument.AType.Default);
3900                                         continue;
3901                                 }
3902
3903                                 if (p_mod != Parameter.Modifier.PARAMS) {
3904                                         p_mod = pd.FixedParameters[i].ModFlags;
3905                                         pt = ptypes [i];
3906                                 } else if (!params_expanded_form) {
3907                                         params_expanded_form = true;
3908                                         pt = ((ElementTypeSpec) pt).Element;
3909                                         i -= 2;
3910                                         continue;
3911                                 }
3912
3913                                 score = 1;
3914                                 if (!params_expanded_form) {
3915                                         if (a.ArgType == Argument.AType.ExtensionType) {
3916                                                 //
3917                                                 // Indentity, implicit reference or boxing conversion must exist for the extension parameter
3918                                                 //
3919                                                 var at = a.Type;
3920                                                 if (at == pt || TypeSpecComparer.IsEqual (at, pt) ||
3921                                                         Convert.ImplicitReferenceConversionExists (a.Expr, pt) ||
3922                                                         Convert.ImplicitBoxingConversion (EmptyExpression.Null, at, pt) != null) {
3923                                                         score = 0;
3924                                                         continue;
3925                                                 }
3926                                         } else {
3927                                                 score = IsArgumentCompatible (ec, a, p_mod & ~Parameter.Modifier.PARAMS, pt);
3928
3929                                                 if (score < 0)
3930                                                         dynamicArgument = true;
3931                                         }
3932                                 }
3933
3934                                 //
3935                                 // It can be applicable in expanded form (when not doing exact match like for delegates)
3936                                 //
3937                                 if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && (restrictions & Restrictions.CovariantDelegate) == 0) {
3938                                         if (!params_expanded_form)
3939                                                 pt = ((ElementTypeSpec) pt).Element;
3940
3941                                         if (score > 0)
3942                                                 score = IsArgumentCompatible (ec, a, Parameter.Modifier.NONE, pt);
3943
3944                                         if (score == 0) {
3945                                                 params_expanded_form = true;
3946                                         } else if (score < 0) {
3947                                                 params_expanded_form = true;
3948                                                 dynamicArgument = true;
3949                                         }
3950                                 }
3951
3952                                 if (score > 0) {
3953                                         if (params_expanded_form)
3954                                                 ++score;
3955                                         return (arg_count - i) * 2 + score;
3956                                 }
3957                         }
3958
3959                         //
3960                         // When params parameter has no argument it will be provided later if the method is the best candidate
3961                         //
3962                         if (arg_count + 1 == pd.Count && (pd.FixedParameters [arg_count].ModFlags & Parameter.Modifier.PARAMS) != 0)
3963                                 params_expanded_form = true;
3964
3965                         //
3966                         // Restore original arguments for dynamic binder to keep the intention of original source code
3967                         //
3968                         if (dynamicArgument)
3969                                 arguments = orig_args;
3970
3971                         return 0;
3972                 }
3973
3974                 //
3975                 // Tests argument compatibility with the parameter
3976                 // The possible return values are
3977                 // 0 - success
3978                 // 1 - modifier mismatch
3979                 // 2 - type mismatch
3980                 // -1 - dynamic binding required
3981                 //
3982                 int IsArgumentCompatible (ResolveContext ec, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter)
3983                 {
3984                         //
3985                         // Types have to be identical when ref or out modifer
3986                         // is used and argument is not of dynamic type
3987                         //
3988                         if ((argument.Modifier | param_mod) != 0) {
3989                                 if (argument.Type != parameter) {
3990                                         //
3991                                         // Do full equality check after quick path
3992                                         //
3993                                         if (!TypeSpecComparer.IsEqual (argument.Type, parameter)) {
3994                                                 //
3995                                                 // Using dynamic for ref/out parameter can still succeed at runtime
3996                                                 //
3997                                                 if (argument.Type == InternalType.Dynamic && argument.Modifier == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
3998                                                         return -1;
3999
4000                                                 return 2;
4001                                         }
4002                                 }
4003
4004                                 if (argument.Modifier != param_mod) {
4005                                         //
4006                                         // Using dynamic for ref/out parameter can still succeed at runtime
4007                                         //
4008                                         if (argument.Type == InternalType.Dynamic && argument.Modifier == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
4009                                                 return -1;
4010
4011                                         return 1;
4012                                 }
4013
4014                         } else {
4015                                 if (argument.Type == InternalType.Dynamic && (restrictions & Restrictions.CovariantDelegate) == 0)
4016                                         return -1;
4017
4018                                 //
4019                                 // Deploy custom error reporting for lambda methods. When probing lambda methods
4020                                 // keep all errors reported in separate set and once we are done and no best
4021                                 // candidate found, this set is used to report more details about what was wrong
4022                                 // with lambda body
4023                                 //
4024                                 if (argument.Expr.Type == InternalType.AnonymousMethod) {
4025                                         if (lambda_conv_msgs == null) {
4026                                                 lambda_conv_msgs = new SessionReportPrinter ();
4027                                                 prev_recorder = ec.Report.SetPrinter (lambda_conv_msgs);
4028                                         }
4029                                 }
4030
4031                                 if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
4032                                         if (lambda_conv_msgs != null) {
4033                                                 lambda_conv_msgs.EndSession ();
4034                                         }
4035
4036                                         return 2;
4037                                 }
4038                         }
4039
4040                         return 0;
4041                 }
4042
4043                 static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q)
4044                 {
4045                         if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
4046                                 return q;
4047                         if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
4048                                 return p;
4049
4050                         var ac_p = p as ArrayContainer;
4051                         if (ac_p != null) {
4052                                 var ac_q = ((ArrayContainer) q);
4053                                 TypeSpec specific = MoreSpecific (ac_p.Element, ac_q.Element);
4054                                 if (specific == ac_p.Element)
4055                                         return p;
4056                                 if (specific == ac_q.Element)
4057                                         return q;
4058                         } else if (TypeManager.IsGenericType (p)) {
4059                                 var pargs = TypeManager.GetTypeArguments (p);
4060                                 var qargs = TypeManager.GetTypeArguments (q);
4061
4062                                 bool p_specific_at_least_once = false;
4063                                 bool q_specific_at_least_once = false;
4064
4065                                 for (int i = 0; i < pargs.Length; i++) {
4066                                         TypeSpec specific = MoreSpecific (pargs[i], qargs[i]);
4067                                         if (specific == pargs[i])
4068                                                 p_specific_at_least_once = true;
4069                                         if (specific == qargs[i])
4070                                                 q_specific_at_least_once = true;
4071                                 }
4072
4073                                 if (p_specific_at_least_once && !q_specific_at_least_once)
4074                                         return p;
4075                                 if (!p_specific_at_least_once && q_specific_at_least_once)
4076                                         return q;
4077                         }
4078
4079                         return null;
4080                 }
4081
4082                 //
4083                 // Find the best method from candidate list
4084                 //
4085                 public T ResolveMember<T> (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember
4086                 {
4087                         List<AmbiguousCandidate> ambiguous_candidates = null;
4088
4089                         MemberSpec best_candidate;
4090                         Arguments best_candidate_args = null;
4091                         bool best_candidate_params = false;
4092                         bool best_candidate_dynamic = false;
4093                         int best_candidate_rate;
4094                         IParametersMember best_parameter_member = null;
4095
4096                         int args_count = args != null ? args.Count : 0;
4097
4098                         Arguments candidate_args = args;
4099                         bool error_mode = false;
4100                         var current_type = rc.CurrentType;
4101                         MemberSpec invocable_member = null;
4102
4103                         // Be careful, cannot return until error reporter is restored
4104                         while (true) {
4105                                 best_candidate = null;
4106                                 best_candidate_rate = int.MaxValue;
4107
4108                                 var type_members = members;
4109                                 try {
4110
4111                                         do {
4112                                                 for (int i = 0; i < type_members.Count; ++i) {
4113                                                         var member = type_members[i];
4114
4115                                                         //
4116                                                         // Methods in a base class are not candidates if any method in a derived
4117                                                         // class is applicable
4118                                                         //
4119                                                         if ((member.Modifiers & Modifiers.OVERRIDE) != 0)
4120                                                                 continue;
4121
4122                                                         if (!error_mode) {
4123                                                                 if (!member.IsAccessible (current_type))
4124                                                                         continue;
4125
4126                                                                 if (rc.Compiler.IsRuntimeBinder && !member.DeclaringType.IsAccessible (current_type))
4127                                                                         continue;
4128                                                         }
4129
4130                                                         IParametersMember pm = member as IParametersMember;
4131                                                         if (pm == null) {
4132                                                                 //
4133                                                                 // Will use it later to report ambiguity between best method and invocable member
4134                                                                 //
4135                                                                 if (Invocation.IsMemberInvocable (member))
4136                                                                         invocable_member = member;
4137
4138                                                                 continue;
4139                                                         }
4140
4141                                                         //
4142                                                         // Overload resolution is looking for base member but using parameter names
4143                                                         // and default values from the closest member. That means to do expensive lookup
4144                                                         // for the closest override for virtual or abstract members
4145                                                         //
4146                                                         if ((member.Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
4147                                                                 var override_params = base_provider.GetOverrideMemberParameters (member);
4148                                                                 if (override_params != null)
4149                                                                         pm = override_params;
4150                                                         }
4151
4152                                                         //
4153                                                         // Check if the member candidate is applicable
4154                                                         //
4155                                                         bool params_expanded_form = false;
4156                                                         bool dynamic_argument = false;
4157                                                         TypeSpec rt = pm.MemberType;
4158                                                         int candidate_rate = IsApplicable (rc, ref candidate_args, args_count, ref member, pm, ref params_expanded_form, ref dynamic_argument, ref rt);
4159
4160                                                         //
4161                                                         // How does it score compare to others
4162                                                         //
4163                                                         if (candidate_rate < best_candidate_rate) {
4164                                                                 best_candidate_rate = candidate_rate;
4165                                                                 best_candidate = member;
4166                                                                 best_candidate_args = candidate_args;
4167                                                                 best_candidate_params = params_expanded_form;
4168                                                                 best_candidate_dynamic = dynamic_argument;
4169                                                                 best_parameter_member = pm;
4170                                                                 best_candidate_return_type = rt;
4171                                                         } else if (candidate_rate == 0) {
4172                                                                 //
4173                                                                 // The member look is done per type for most operations but sometimes
4174                                                                 // it's not possible like for binary operators overload because they
4175                                                                 // are unioned between 2 sides
4176                                                                 //
4177                                                                 if ((restrictions & Restrictions.BaseMembersIncluded) != 0) {
4178                                                                         if (TypeSpec.IsBaseClass (best_candidate.DeclaringType, member.DeclaringType, true))
4179                                                                                 continue;
4180                                                                 }
4181
4182                                                                 // Is the new candidate better
4183                                                                 if (BetterFunction (rc, candidate_args, member, pm.Parameters, params_expanded_form, best_candidate, best_parameter_member.Parameters, best_candidate_params)) {
4184                                                                         best_candidate = member;
4185                                                                         best_candidate_args = candidate_args;
4186                                                                         best_candidate_params = params_expanded_form;
4187                                                                         best_candidate_dynamic = dynamic_argument;
4188                                                                         best_parameter_member = pm;
4189                                                                         best_candidate_return_type = rt;
4190                                                                 } else {
4191                                                                         // It's not better but any other found later could be but we are not sure yet
4192                                                                         if (ambiguous_candidates == null)
4193                                                                                 ambiguous_candidates = new List<AmbiguousCandidate> ();
4194
4195                                                                         ambiguous_candidates.Add (new AmbiguousCandidate (member, pm.Parameters, params_expanded_form));
4196                                                                 }
4197                                                         }
4198
4199                                                         // Restore expanded arguments
4200                                                         if (candidate_args != args)
4201                                                                 candidate_args = args;
4202                                                 }
4203                                         } while (best_candidate_rate != 0 && (type_members = base_provider.GetBaseMembers (type_members[0].DeclaringType.BaseType)) != null);
4204                                 } finally {
4205                                         if (prev_recorder != null)
4206                                                 rc.Report.SetPrinter (prev_recorder);
4207                                 }
4208
4209                                 //
4210                                 // We've found exact match
4211                                 //
4212                                 if (best_candidate_rate == 0)
4213                                         break;
4214
4215                                 //
4216                                 // Try extension methods lookup when no ordinary method match was found and provider enables it
4217                                 //
4218                                 if (!error_mode) {
4219                                         var emg = base_provider.LookupExtensionMethod (rc);
4220                                         if (emg != null) {
4221                                                 emg = emg.OverloadResolve (rc, ref args, null, restrictions);
4222                                                 if (emg != null) {
4223                                                         best_candidate_extension_group = emg;
4224                                                         return (T) (MemberSpec) emg.BestCandidate;
4225                                                 }
4226                                         }
4227                                 }
4228
4229                                 // Don't run expensive error reporting mode for probing
4230                                 if (IsProbingOnly)
4231                                         return null;
4232
4233                                 if (error_mode)
4234                                         break;
4235
4236                                 lambda_conv_msgs = null;
4237                                 error_mode = true;
4238                         }
4239
4240                         //
4241                         // No best member match found, report an error
4242                         //
4243                         if (best_candidate_rate != 0 || error_mode) {
4244                                 ReportOverloadError (rc, best_candidate, best_parameter_member, best_candidate_args, best_candidate_params);
4245                                 return null;
4246                         }
4247
4248                         if (best_candidate_dynamic) {
4249                                 if (args[0].ArgType == Argument.AType.ExtensionType) {
4250                                         rc.Report.Error (1973, loc,
4251                                                 "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",
4252                                                 args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ());
4253                                 }
4254
4255                                 BestCandidateIsDynamic = true;
4256                                 return null;
4257                         }
4258
4259                         if (ambiguous_candidates != null) {
4260                                 //
4261                                 // Now check that there are no ambiguities i.e the selected method
4262                                 // should be better than all the others
4263                                 //
4264                                 for (int ix = 0; ix < ambiguous_candidates.Count; ix++) {
4265                                         var candidate = ambiguous_candidates [ix];
4266
4267                                         if (!BetterFunction (rc, best_candidate_args, best_candidate, best_parameter_member.Parameters, best_candidate_params, candidate.Member, candidate.Parameters, candidate.Expanded)) {
4268                                                 var ambiguous = candidate.Member;
4269                                                 if (custom_errors == null || !custom_errors.AmbiguousCandidates (rc, best_candidate, ambiguous)) {
4270                                                         rc.Report.SymbolRelatedToPreviousError (best_candidate);
4271                                                         rc.Report.SymbolRelatedToPreviousError (ambiguous);
4272                                                         rc.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
4273                                                                 best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ());
4274                                                 }
4275
4276                                                 return (T) best_candidate;
4277                                         }
4278                                 }
4279                         }
4280
4281                         if (invocable_member != null) {
4282                                 rc.Report.SymbolRelatedToPreviousError (best_candidate);
4283                                 rc.Report.SymbolRelatedToPreviousError (invocable_member);
4284                                 rc.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and invocable non-method `{1}'. Using method group",
4285                                         best_candidate.GetSignatureForError (), invocable_member.GetSignatureForError ());
4286                         }
4287
4288                         //
4289                         // And now check if the arguments are all
4290                         // compatible, perform conversions if
4291                         // necessary etc. and return if everything is
4292                         // all right
4293                         //
4294                         if (!VerifyArguments (rc, ref best_candidate_args, best_candidate, best_parameter_member, best_candidate_params))
4295                                 return null;
4296
4297                         if (best_candidate == null)
4298                                 return null;
4299
4300                         //
4301                         // Check ObsoleteAttribute on the best method
4302                         //
4303                         ObsoleteAttribute oa = best_candidate.GetAttributeObsolete ();
4304                         if (oa != null && !rc.IsObsolete)
4305                                 AttributeTester.Report_ObsoleteMessage (oa, best_candidate.GetSignatureForError (), loc, rc.Report);
4306
4307                         best_candidate.MemberDefinition.SetIsUsed ();
4308
4309                         args = best_candidate_args;
4310                         return (T) best_candidate;
4311                 }
4312
4313                 public MethodSpec ResolveOperator (ResolveContext rc, ref Arguments args)
4314                 {
4315                         return ResolveMember<MethodSpec> (rc, ref args);
4316                 }
4317
4318                 void ReportArgumentMismatch (ResolveContext ec, int idx, MemberSpec method,
4319                                                                                                         Argument a, AParametersCollection expected_par, TypeSpec paramType)
4320                 {
4321                         if (custom_errors != null && custom_errors.ArgumentMismatch (ec, method, a, idx))
4322                                 return;
4323
4324                         if (a is CollectionElementInitializer.ElementInitializerArgument) {
4325                                 ec.Report.SymbolRelatedToPreviousError (method);
4326                                 if ((expected_par.FixedParameters[idx].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
4327                                         ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
4328                                                 TypeManager.CSharpSignature (method));
4329                                         return;
4330                                 }
4331                                 ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
4332                                           TypeManager.CSharpSignature (method));
4333                         } else if (IsDelegateInvoke) {
4334                                 ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
4335                                         DelegateType.GetSignatureForError ());
4336                         } else {
4337                                 ec.Report.SymbolRelatedToPreviousError (method);
4338                                 ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
4339                                         method.GetSignatureForError ());
4340                         }
4341
4342                         Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters[idx].ModFlags;
4343
4344                         string index = (idx + 1).ToString ();
4345                         if (((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) ^
4346                                 (a.Modifier & (Parameter.Modifier.REF | Parameter.Modifier.OUT))) != 0) {
4347                                 if ((mod & Parameter.Modifier.ISBYREF) == 0)
4348                                         ec.Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
4349                                                 index, Parameter.GetModifierSignature (a.Modifier));
4350                                 else
4351                                         ec.Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
4352                                                 index, Parameter.GetModifierSignature (mod));
4353                         } else {
4354                                 string p1 = a.GetSignatureForError ();
4355                                 string p2 = TypeManager.CSharpName (paramType);
4356
4357                                 if (p1 == p2) {
4358                                         ec.Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
4359                                         ec.Report.SymbolRelatedToPreviousError (a.Expr.Type);
4360                                         ec.Report.SymbolRelatedToPreviousError (paramType);
4361                                 }
4362
4363                                 ec.Report.Error (1503, loc,
4364                                         "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
4365                         }
4366                 }
4367
4368                 //
4369                 // We have failed to find exact match so we return error info about the closest match
4370                 //
4371                 void ReportOverloadError (ResolveContext rc, MemberSpec best_candidate, IParametersMember pm, Arguments args, bool params_expanded)
4372                 {
4373                         int ta_count = type_arguments == null ? 0 : type_arguments.Count;
4374                         int arg_count = args == null ? 0 : args.Count;
4375
4376                         if (ta_count != best_candidate.Arity && (ta_count > 0 || ((IParametersMember) best_candidate).Parameters.IsEmpty)) {
4377                                 var mg = new MethodGroupExpr (new [] { best_candidate }, best_candidate.DeclaringType, loc);
4378                                 mg.Error_TypeArgumentsCannotBeUsed (rc.Report, loc, best_candidate, ta_count);
4379                                 return;
4380                         }
4381
4382                         if (lambda_conv_msgs != null) {
4383                                 if (lambda_conv_msgs.Merge (rc.Report.Printer))
4384                                         return;
4385                         }
4386
4387                         //
4388                         // For candidates which match on parameters count report more details about incorrect arguments
4389                         //
4390                         if (pm != null) {
4391                                 int unexpanded_count = pm.Parameters.HasParams ? pm.Parameters.Count - 1 : pm.Parameters.Count;
4392                                 if (pm.Parameters.Count == arg_count || params_expanded || unexpanded_count == arg_count) {
4393                                         // Reject any inaccessible member
4394                                         if (!best_candidate.IsAccessible (rc.CurrentType) || !best_candidate.DeclaringType.IsAccessible (rc.CurrentType)) {
4395                                                 rc.Report.SymbolRelatedToPreviousError (best_candidate);
4396                                                 Expression.ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
4397                                                 return;
4398                                         }
4399
4400                                         var ms = best_candidate as MethodSpec;
4401                                         if (ms != null && ms.IsGeneric) {
4402                                                 bool constr_ok = true;
4403                                                 if (ms.TypeArguments != null)
4404                                                         constr_ok = new ConstraintChecker (rc.MemberContext).CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc);
4405
4406                                                 if (ta_count == 0) {
4407                                                         if (custom_errors != null && custom_errors.TypeInferenceFailed (rc, best_candidate))
4408                                                                 return;
4409
4410                                                         if (constr_ok) {
4411                                                                 rc.Report.Error (411, loc,
4412                                                                         "The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly",
4413                                                                         ms.GetGenericMethodDefinition ().GetSignatureForError ());
4414                                                         }
4415
4416                                                         return;
4417                                                 }
4418                                         }
4419
4420                                         VerifyArguments (rc, ref args, best_candidate, pm, params_expanded);
4421                                         return;
4422                                 }
4423                         }
4424
4425                         //
4426                         // We failed to find any method with correct argument count, report best candidate
4427                         //
4428                         if (custom_errors != null && custom_errors.NoArgumentMatch (rc, best_candidate))
4429                                 return;
4430
4431                         if (best_candidate.Kind == MemberKind.Constructor) {
4432                                 rc.Report.SymbolRelatedToPreviousError (best_candidate);
4433                                 Error_ConstructorMismatch (rc, best_candidate.DeclaringType, arg_count, loc);
4434                         } else if (IsDelegateInvoke) {
4435                                 rc.Report.SymbolRelatedToPreviousError (DelegateType);
4436                                 rc.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
4437                                         DelegateType.GetSignatureForError (), arg_count.ToString ());
4438                         } else {
4439                                 string name = best_candidate.Kind == MemberKind.Indexer ? "this" : best_candidate.Name;
4440                                 rc.Report.SymbolRelatedToPreviousError (best_candidate);
4441                                 rc.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
4442                                         name, arg_count.ToString ());
4443                         }
4444                 }
4445
4446                 bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded)
4447                 {
4448                         var pd = pm.Parameters;
4449                         TypeSpec[] ptypes = ((IParametersMember) member).Parameters.Types;
4450
4451                         Parameter.Modifier p_mod = 0;
4452                         TypeSpec pt = null;
4453                         int a_idx = 0, a_pos = 0;
4454                         Argument a = null;
4455                         ArrayInitializer params_initializers = null;
4456                         bool has_unsafe_arg = pm.MemberType.IsPointer;
4457                         int arg_count = args == null ? 0 : args.Count;
4458
4459                         for (; a_idx < arg_count; a_idx++, ++a_pos) {
4460                                 a = args[a_idx];
4461                                 if (p_mod != Parameter.Modifier.PARAMS) {
4462                                         p_mod = pd.FixedParameters[a_idx].ModFlags;
4463                                         pt = ptypes[a_idx];
4464                                         has_unsafe_arg |= pt.IsPointer;
4465
4466                                         if (p_mod == Parameter.Modifier.PARAMS) {
4467                                                 if (chose_params_expanded) {
4468                                                         params_initializers = new ArrayInitializer (arg_count - a_idx, a.Expr.Location);
4469                                                         pt = TypeManager.GetElementType (pt);
4470                                                 }
4471                                         }
4472                                 }
4473
4474                                 //
4475                                 // Types have to be identical when ref or out modifer is used 
4476                                 //
4477                                 if (a.Modifier != 0 || (p_mod & ~Parameter.Modifier.PARAMS) != 0) {
4478                                         if ((p_mod & ~Parameter.Modifier.PARAMS) != a.Modifier)
4479                                                 break;
4480
4481                                         if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt))
4482                                                 continue;
4483
4484                                         break;
4485                                 }
4486
4487                                 NamedArgument na = a as NamedArgument;
4488                                 if (na != null) {
4489                                         int name_index = pd.GetParameterIndexByName (na.Name);
4490                                         if (name_index < 0 || name_index >= pd.Count) {
4491                                                 if (IsDelegateInvoke) {
4492                                                         ec.Report.SymbolRelatedToPreviousError (DelegateType);
4493                                                         ec.Report.Error (1746, na.Location,
4494                                                                 "The delegate `{0}' does not contain a parameter named `{1}'",
4495                                                                 DelegateType.GetSignatureForError (), na.Name);
4496                                                 } else {
4497                                                         ec.Report.SymbolRelatedToPreviousError (member);
4498                                                         ec.Report.Error (1739, na.Location,
4499                                                                 "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
4500                                                                 TypeManager.CSharpSignature (member), na.Name);
4501                                                 }
4502                                         } else if (args[name_index] != a) {
4503                                                 if (IsDelegateInvoke)
4504                                                         ec.Report.SymbolRelatedToPreviousError (DelegateType);
4505                                                 else
4506                                                         ec.Report.SymbolRelatedToPreviousError (member);
4507
4508                                                 ec.Report.Error (1744, na.Location,
4509                                                         "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
4510                                                         na.Name);
4511                                         }
4512                                 }
4513                                 
4514                                 if (a.Expr.Type == InternalType.Dynamic)
4515                                         continue;
4516
4517                                 if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (a.Expr, pt)) {
4518                                         custom_errors.NoArgumentMatch (ec, member);
4519                                         return false;
4520                                 }
4521
4522                                 Expression conv = null;
4523                                 if (a.ArgType == Argument.AType.ExtensionType) {
4524                                         if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt)) {
4525                                                 conv = a.Expr;
4526                                         } else {
4527                                                 conv = Convert.ImplicitReferenceConversion (a.Expr, pt, false);
4528                                                 if (conv == null)
4529                                                         conv = Convert.ImplicitBoxingConversion (a.Expr, a.Expr.Type, pt);
4530                                         }
4531                                 } else {
4532                                         conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
4533                                 }
4534
4535                                 if (conv == null)
4536                                         break;
4537
4538                                 //
4539                                 // Convert params arguments to an array initializer
4540                                 //
4541                                 if (params_initializers != null) {
4542                                         // we choose to use 'a.Expr' rather than 'conv' so that
4543                                         // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
4544                                         params_initializers.Add (a.Expr);
4545                                         args.RemoveAt (a_idx--);
4546                                         --arg_count;
4547                                         continue;
4548                                 }
4549
4550                                 // Update the argument with the implicit conversion
4551                                 a.Expr = conv;
4552                         }
4553
4554                         if (a_idx != arg_count) {
4555                                 ReportArgumentMismatch (ec, a_pos, member, a, pd, pt);
4556                                 return false;
4557                         }
4558
4559                         //
4560                         // Fill not provided arguments required by params modifier
4561                         //
4562                         if (params_initializers == null && pd.HasParams && arg_count + 1 == pd.Count) {
4563                                 if (args == null)
4564                                         args = new Arguments (1);
4565
4566                                 pt = ptypes[pd.Count - 1];
4567                                 pt = TypeManager.GetElementType (pt);
4568                                 has_unsafe_arg |= pt.IsPointer;
4569                                 params_initializers = new ArrayInitializer (0, loc);
4570                         }
4571
4572                         //
4573                         // Append an array argument with all params arguments
4574                         //
4575                         if (params_initializers != null) {
4576                                 args.Add (new Argument (
4577                                         new ArrayCreation (new TypeExpression (pt, loc), params_initializers, loc).Resolve (ec)));
4578                                 arg_count++;
4579                         }
4580
4581                         if (has_unsafe_arg && !ec.IsUnsafe) {
4582                                 Expression.UnsafeError (ec, loc);
4583                         }
4584
4585                         //
4586                         // We could infer inaccesible type arguments
4587                         //
4588                         if (type_arguments == null && member.IsGeneric) {
4589                                 var ms = (MethodSpec) member;
4590                                 foreach (var ta in ms.TypeArguments) {
4591                                         if (!ta.IsAccessible (ec.CurrentType)) {
4592                                                 ec.Report.SymbolRelatedToPreviousError (ta);
4593                                                 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
4594                                                 break;
4595                                         }
4596                                 }
4597                         }
4598
4599                         return true;
4600                 }
4601         }
4602
4603         public class ConstantExpr : MemberExpr
4604         {
4605                 ConstSpec constant;
4606
4607                 public ConstantExpr (ConstSpec constant, Location loc)
4608                 {
4609                         this.constant = constant;
4610                         this.loc = loc;
4611                 }
4612
4613                 public override string Name {
4614                         get { throw new NotImplementedException (); }
4615                 }
4616
4617                 public override bool IsInstance {
4618                         get { return !IsStatic; }
4619                 }
4620
4621                 public override bool IsStatic {
4622                         get { return true; }
4623                 }
4624
4625                 protected override TypeSpec DeclaringType {
4626                         get { return constant.DeclaringType; }
4627                 }
4628
4629                 public override Expression CreateExpressionTree (ResolveContext ec)
4630                 {
4631                         throw new NotSupportedException ("ET");
4632                 }
4633
4634                 protected override Expression DoResolve (ResolveContext rc)
4635                 {
4636                         ResolveInstanceExpression (rc, null);
4637                         DoBestMemberChecks (rc, constant);
4638
4639                         var c = constant.GetConstant (rc);
4640
4641                         // Creates reference expression to the constant value
4642                         return Constant.CreateConstant (rc, constant.MemberType, c.GetValue (), loc);
4643                 }
4644
4645                 public override void Emit (EmitContext ec)
4646                 {
4647                         throw new NotSupportedException ();
4648                 }
4649
4650                 public override string GetSignatureForError ()
4651                 {
4652                         return constant.GetSignatureForError ();
4653                 }
4654
4655                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
4656                 {
4657                         Error_TypeArgumentsCannotBeUsed (ec.Report, "constant", GetSignatureForError (), loc);
4658                 }
4659         }
4660
4661         /// <summary>
4662         ///   Fully resolved expression that evaluates to a Field
4663         /// </summary>
4664         public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference {
4665                 protected FieldSpec spec;
4666                 VariableInfo variable_info;
4667                 
4668                 LocalTemporary temp;
4669                 bool prepared;
4670                 
4671                 protected FieldExpr (Location l)
4672                 {
4673                         loc = l;
4674                 }
4675
4676                 public FieldExpr (FieldSpec spec, Location loc)
4677                 {
4678                         this.spec = spec;
4679                         this.loc = loc;
4680
4681                         type = spec.MemberType;
4682                 }
4683                 
4684                 public FieldExpr (FieldBase fi, Location l)
4685                         : this (fi.Spec, l)
4686                 {
4687                 }
4688
4689                 #region Properties
4690
4691                 public override string Name {
4692                         get {
4693                                 return spec.Name;
4694                         }
4695                 }
4696
4697                 public bool IsHoisted {
4698                         get {
4699                                 IVariableReference hv = InstanceExpression as IVariableReference;
4700                                 return hv != null && hv.IsHoisted;
4701                         }
4702                 }
4703
4704                 public override bool IsInstance {
4705                         get {
4706                                 return !spec.IsStatic;
4707                         }
4708                 }
4709
4710                 public override bool IsStatic {
4711                         get {
4712                                 return spec.IsStatic;
4713                         }
4714                 }
4715
4716                 public FieldSpec Spec {
4717                         get {
4718                                 return spec;
4719                         }
4720                 }
4721
4722                 protected override TypeSpec DeclaringType {
4723                         get {
4724                                 return spec.DeclaringType;
4725                         }
4726                 }
4727
4728                 public VariableInfo VariableInfo {
4729                         get {
4730                                 return variable_info;
4731                         }
4732                 }
4733
4734 #endregion
4735
4736                 public override string GetSignatureForError ()
4737                 {
4738                         return TypeManager.GetFullNameSignature (spec);
4739                 }
4740
4741                 public bool IsMarshalByRefAccess ()
4742                 {
4743                         // Checks possible ldflda of field access expression
4744                         return !spec.IsStatic && TypeManager.IsValueType (spec.MemberType) &&
4745                                 TypeSpec.IsBaseClass (spec.DeclaringType, TypeManager.mbr_type, false) &&
4746                                 !(InstanceExpression is This);
4747                 }
4748
4749                 public void SetHasAddressTaken ()
4750                 {
4751                         IVariableReference vr = InstanceExpression as IVariableReference;
4752                         if (vr != null)
4753                                 vr.SetHasAddressTaken ();
4754                 }
4755
4756                 public override Expression CreateExpressionTree (ResolveContext ec)
4757                 {
4758                         Expression instance;
4759                         if (InstanceExpression == null) {
4760                                 instance = new NullLiteral (loc);
4761                         } else {
4762                                 instance = InstanceExpression.CreateExpressionTree (ec);
4763                         }
4764
4765                         Arguments args = Arguments.CreateForExpressionTree (ec, null,
4766                                 instance,
4767                                 CreateTypeOfExpression ());
4768
4769                         return CreateExpressionFactoryCall (ec, "Field", args);
4770                 }
4771
4772                 public Expression CreateTypeOfExpression ()
4773                 {
4774                         return new TypeOfField (spec, loc);
4775                 }
4776
4777                 protected override Expression DoResolve (ResolveContext ec)
4778                 {
4779                         return DoResolve (ec, null);
4780                 }
4781
4782                 Expression DoResolve (ResolveContext ec, Expression rhs)
4783                 {
4784                         bool lvalue_instance = rhs != null && IsInstance && spec.DeclaringType.IsStruct;
4785
4786                         if (ResolveInstanceExpression (ec, rhs)) {
4787                                 // Resolve the field's instance expression while flow analysis is turned
4788                                 // off: when accessing a field "a.b", we must check whether the field
4789                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4790
4791                                 if (lvalue_instance) {
4792                                         using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4793                                                 bool out_access = rhs == EmptyExpression.OutAccess.Instance || rhs == EmptyExpression.LValueMemberOutAccess;
4794
4795                                                 Expression right_side =
4796                                                         out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
4797
4798                                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
4799                                         }
4800                                 } else {
4801                                         using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4802                                                 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
4803                                         }
4804                                 }
4805
4806                                 if (InstanceExpression == null)
4807                                         return null;
4808                         }
4809
4810                         DoBestMemberChecks (ec, spec);
4811
4812                         var fb = spec as FixedFieldSpec;
4813                         IVariableReference var = InstanceExpression as IVariableReference;
4814
4815                         if (lvalue_instance && var != null && var.VariableInfo != null) {
4816                                 var.VariableInfo.SetFieldAssigned (ec, Name);
4817                         }
4818                         
4819                         if (fb != null) {
4820                                 IFixedExpression fe = InstanceExpression as IFixedExpression;
4821                                 if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
4822                                         ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
4823                                 }
4824
4825                                 if (InstanceExpression.eclass != ExprClass.Variable) {
4826                                         ec.Report.SymbolRelatedToPreviousError (spec);
4827                                         ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
4828                                                 TypeManager.GetFullNameSignature (spec));
4829                                 } else if (var != null && var.IsHoisted) {
4830                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
4831                                 }
4832                                 
4833                                 return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
4834                         }
4835
4836                         eclass = ExprClass.Variable;
4837
4838                         // If the instance expression is a local variable or parameter.
4839                         if (var == null || var.VariableInfo == null)
4840                                 return this;
4841
4842                         VariableInfo vi = var.VariableInfo;
4843                         if (!vi.IsFieldAssigned (ec, Name, loc))
4844                                 return null;
4845
4846                         variable_info = vi.GetSubStruct (Name);
4847                         return this;
4848                 }
4849
4850                 static readonly int [] codes = {
4851                         191,    // instance, write access
4852                         192,    // instance, out access
4853                         198,    // static, write access
4854                         199,    // static, out access
4855                         1648,   // member of value instance, write access
4856                         1649,   // member of value instance, out access
4857                         1650,   // member of value static, write access
4858                         1651    // member of value static, out access
4859                 };
4860
4861                 static readonly string [] msgs = {
4862                         /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
4863                         /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4864                         /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4865                         /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
4866                         /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
4867                         /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4868                         /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4869                         /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
4870                 };
4871
4872                 // The return value is always null.  Returning a value simplifies calling code.
4873                 Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
4874                 {
4875                         int i = 0;
4876                         if (right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess)
4877                                 i += 1;
4878                         if (IsStatic)
4879                                 i += 2;
4880                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
4881                                 i += 4;
4882                         ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
4883
4884                         return null;
4885                 }
4886                 
4887                 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4888                 {
4889                         Expression e = DoResolve (ec, right_side);
4890
4891                         if (e == null)
4892                                 return null;
4893
4894                         spec.MemberDefinition.SetIsAssigned ();
4895
4896                         if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess.Instance) &&
4897                                         (spec.Modifiers & Modifiers.VOLATILE) != 0) {
4898                                 ec.Report.Warning (420, 1, loc,
4899                                         "`{0}': A volatile field references will not be treated as volatile",
4900                                         spec.GetSignatureForError ());
4901                         }
4902
4903                         if (spec.IsReadOnly) {
4904                                 // InitOnly fields can only be assigned in constructors or initializers
4905                                 if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
4906                                         return Report_AssignToReadonly (ec, right_side);
4907
4908                                 if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
4909
4910                                         // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
4911                                         if (ec.CurrentMemberDefinition.Parent.Definition != spec.DeclaringType.GetDefinition ())
4912                                                 return Report_AssignToReadonly (ec, right_side);
4913                                         // static InitOnly fields cannot be assigned-to in an instance constructor
4914                                         if (IsStatic && !ec.IsStatic)
4915                                                 return Report_AssignToReadonly (ec, right_side);
4916                                         // instance constructors can't modify InitOnly fields of other instances of the same type
4917                                         if (!IsStatic && !(InstanceExpression is This))
4918                                                 return Report_AssignToReadonly (ec, right_side);
4919                                 }
4920                         }
4921
4922                         if (right_side == EmptyExpression.OutAccess.Instance &&
4923                                 !IsStatic && !(InstanceExpression is This) && TypeManager.mbr_type != null && TypeSpec.IsBaseClass (spec.DeclaringType, TypeManager.mbr_type, false)) {
4924                                 ec.Report.SymbolRelatedToPreviousError (spec.DeclaringType);
4925                                 ec.Report.Warning (197, 1, loc,
4926                                                 "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",
4927                                                 GetSignatureForError ());
4928                         }
4929
4930                         eclass = ExprClass.Variable;
4931                         return this;
4932                 }
4933
4934                 public override int GetHashCode ()
4935                 {
4936                         return spec.GetHashCode ();
4937                 }
4938                 
4939                 public bool IsFixed {
4940                         get {
4941                                 //
4942                                 // A variable of the form V.I is fixed when V is a fixed variable of a struct type
4943                                 //
4944                                 IVariableReference variable = InstanceExpression as IVariableReference;
4945                                 if (variable != null)
4946                                         return InstanceExpression.Type.IsStruct && variable.IsFixed;
4947
4948                                 IFixedExpression fe = InstanceExpression as IFixedExpression;
4949                                 return fe != null && fe.IsFixed;
4950                         }
4951                 }
4952
4953                 public override bool Equals (object obj)
4954                 {
4955                         FieldExpr fe = obj as FieldExpr;
4956                         if (fe == null)
4957                                 return false;
4958
4959                         if (spec != fe.spec)
4960                                 return false;
4961
4962                         if (InstanceExpression == null || fe.InstanceExpression == null)
4963                                 return true;
4964
4965                         return InstanceExpression.Equals (fe.InstanceExpression);
4966                 }
4967                 
4968                 public void Emit (EmitContext ec, bool leave_copy)
4969                 {
4970                         bool is_volatile = false;
4971
4972                         if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
4973                                 is_volatile = true;
4974
4975                         spec.MemberDefinition.SetIsUsed ();
4976                         
4977                         if (IsStatic){
4978                                 if (is_volatile)
4979                                         ec.Emit (OpCodes.Volatile);
4980
4981                                 ec.Emit (OpCodes.Ldsfld, spec);
4982                         } else {
4983                                 if (!prepared)
4984                                         EmitInstance (ec, false);
4985
4986                                 // Optimization for build-in types
4987                                 if (TypeManager.IsStruct (type) && type == ec.MemberContext.CurrentType && InstanceExpression.Type == type) {
4988                                         ec.EmitLoadFromPtr (type);
4989                                 } else {
4990                                         var ff = spec as FixedFieldSpec;
4991                                         if (ff != null) {
4992                                                 ec.Emit (OpCodes.Ldflda, spec);
4993                                                 ec.Emit (OpCodes.Ldflda, ff.Element);
4994                                         } else {
4995                                                 if (is_volatile)
4996                                                         ec.Emit (OpCodes.Volatile);
4997
4998                                                 ec.Emit (OpCodes.Ldfld, spec);
4999                                         }
5000                                 }
5001                         }
5002
5003                         if (leave_copy) {
5004                                 ec.Emit (OpCodes.Dup);
5005                                 if (!IsStatic) {
5006                                         temp = new LocalTemporary (this.Type);
5007                                         temp.Store (ec);
5008                                 }
5009                         }
5010                 }
5011
5012                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5013                 {
5014                         prepared = prepare_for_load && !(source is DynamicExpressionStatement);
5015                         if (IsInstance)
5016                                 EmitInstance (ec, prepared);
5017
5018                         source.Emit (ec);
5019                         if (leave_copy) {
5020                                 ec.Emit (OpCodes.Dup);
5021                                 if (!IsStatic) {
5022                                         temp = new LocalTemporary (this.Type);
5023                                         temp.Store (ec);
5024                                 }
5025                         }
5026
5027                         if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
5028                                 ec.Emit (OpCodes.Volatile);
5029                                         
5030                         spec.MemberDefinition.SetIsAssigned ();
5031
5032                         if (IsStatic)
5033                                 ec.Emit (OpCodes.Stsfld, spec);
5034                         else
5035                                 ec.Emit (OpCodes.Stfld, spec);
5036                         
5037                         if (temp != null) {
5038                                 temp.Emit (ec);
5039                                 temp.Release (ec);
5040                                 temp = null;
5041                         }
5042                 }
5043
5044                 public override void Emit (EmitContext ec)
5045                 {
5046                         Emit (ec, false);
5047                 }
5048
5049                 public override void EmitSideEffect (EmitContext ec)
5050                 {
5051                         bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
5052
5053                         if (is_volatile) // || is_marshal_by_ref ())
5054                                 base.EmitSideEffect (ec);
5055                 }
5056
5057                 public void AddressOf (EmitContext ec, AddressOp mode)
5058                 {
5059                         if ((mode & AddressOp.Store) != 0)
5060                                 spec.MemberDefinition.SetIsAssigned ();
5061                         if ((mode & AddressOp.Load) != 0)
5062                                 spec.MemberDefinition.SetIsUsed ();
5063
5064                         //
5065                         // Handle initonly fields specially: make a copy and then
5066                         // get the address of the copy.
5067                         //
5068                         bool need_copy;
5069                         if (spec.IsReadOnly){
5070                                 need_copy = true;
5071                                 if (ec.HasSet (EmitContext.Options.ConstructorScope)){
5072                                         if (IsStatic){
5073                                                 if (ec.IsStatic)
5074                                                         need_copy = false;
5075                                         } else
5076                                                 need_copy = false;
5077                                 }
5078                         } else
5079                                 need_copy = false;
5080                         
5081                         if (need_copy){
5082                                 LocalBuilder local;
5083                                 Emit (ec);
5084                                 local = ec.DeclareLocal (type, false);
5085                                 ec.Emit (OpCodes.Stloc, local);
5086                                 ec.Emit (OpCodes.Ldloca, local);
5087                                 return;
5088                         }
5089
5090
5091                         if (IsStatic){
5092                                 ec.Emit (OpCodes.Ldsflda, spec);
5093                         } else {
5094                                 if (!prepared)
5095                                         EmitInstance (ec, false);
5096                                 ec.Emit (OpCodes.Ldflda, spec);
5097                         }
5098                 }
5099
5100                 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
5101                 {
5102                         return MakeExpression (ctx);
5103                 }
5104
5105                 public override SLE.Expression MakeExpression (BuilderContext ctx)
5106                 {
5107                         return SLE.Expression.Field (
5108                                 IsStatic ? null : InstanceExpression.MakeExpression (ctx),
5109                                 spec.GetMetaInfo ());
5110                 }
5111
5112                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
5113                 {
5114                         Error_TypeArgumentsCannotBeUsed (ec.Report, "field", GetSignatureForError (), loc);
5115                 }
5116         }
5117
5118         
5119         /// <summary>
5120         ///   Expression that evaluates to a Property.  The Assign class
5121         ///   might set the `Value' expression if we are in an assignment.
5122         ///
5123         ///   This is not an LValue because we need to re-write the expression, we
5124         ///   can not take data from the stack and store it.  
5125         /// </summary>
5126         class PropertyExpr : PropertyOrIndexerExpr<PropertySpec>
5127         {
5128                 public PropertyExpr (PropertySpec spec, Location l)
5129                         : base (l)
5130                 {
5131                         best_candidate = spec;
5132                         type = spec.MemberType;
5133                 }
5134
5135                 #region Properties
5136
5137                 protected override TypeSpec DeclaringType {
5138                         get {
5139                                 return best_candidate.DeclaringType;
5140                         }
5141                 }
5142
5143                 public override string Name {
5144                         get {
5145                                 return best_candidate.Name;
5146                         }
5147                 }
5148
5149                 public override bool IsInstance {
5150                         get {
5151                                 return !IsStatic;
5152                         }
5153                 }
5154
5155                 public override bool IsStatic {
5156                         get {
5157                                 return best_candidate.IsStatic;
5158                         }
5159                 }
5160
5161                 public PropertySpec PropertyInfo {
5162                         get {
5163                                 return best_candidate;
5164                         }
5165                 }
5166
5167                 #endregion
5168
5169                 public override Expression CreateExpressionTree (ResolveContext ec)
5170                 {
5171                         Arguments args;
5172                         if (IsSingleDimensionalArrayLength ()) {
5173                                 args = new Arguments (1);
5174                                 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5175                                 return CreateExpressionFactoryCall (ec, "ArrayLength", args);
5176                         }
5177
5178                         args = new Arguments (2);
5179                         if (InstanceExpression == null)
5180                                 args.Add (new Argument (new NullLiteral (loc)));
5181                         else
5182                                 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5183                         args.Add (new Argument (new TypeOfMethod (Getter, loc)));
5184                         return CreateExpressionFactoryCall (ec, "Property", args);
5185                 }
5186
5187                 public Expression CreateSetterTypeOfExpression ()
5188                 {
5189                         return new TypeOfMethod (Setter, loc);
5190                 }
5191
5192                 public override string GetSignatureForError ()
5193                 {
5194                         return best_candidate.GetSignatureForError ();
5195                 }
5196
5197                 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
5198                 {
5199                         return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo ());
5200                 }
5201
5202                 public override SLE.Expression MakeExpression (BuilderContext ctx)
5203                 {
5204                         return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo ());
5205                 }
5206
5207                 void Error_PropertyNotValid (ResolveContext ec)
5208                 {
5209                         ec.Report.SymbolRelatedToPreviousError (best_candidate);
5210                         ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language",
5211                                 GetSignatureForError ());
5212                 }
5213
5214                 bool IsSingleDimensionalArrayLength ()
5215                 {
5216                         if (best_candidate.DeclaringType != TypeManager.array_type || !best_candidate.HasGet || Name != "Length")
5217                                 return false;
5218
5219                         ArrayContainer ac = InstanceExpression.Type as ArrayContainer;
5220                         return ac != null && ac.Rank == 1;
5221                 }
5222
5223                 public override void Emit (EmitContext ec, bool leave_copy)
5224                 {
5225                         //
5226                         // Special case: length of single dimension array property is turned into ldlen
5227                         //
5228                         if (IsSingleDimensionalArrayLength ()) {
5229                                 if (!prepared)
5230                                         EmitInstance (ec, false);
5231                                 ec.Emit (OpCodes.Ldlen);
5232                                 ec.Emit (OpCodes.Conv_I4);
5233                                 return;
5234                         }
5235
5236                         Invocation.EmitCall (ec, InstanceExpression, Getter, null, loc, prepared, false);
5237                         
5238                         if (leave_copy) {
5239                                 ec.Emit (OpCodes.Dup);
5240                                 if (!IsStatic) {
5241                                         temp = new LocalTemporary (this.Type);
5242                                         temp.Store (ec);
5243                                 }
5244                         }
5245                 }
5246
5247                 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5248                 {
5249                         Arguments args;
5250
5251                         if (prepare_for_load && !(source is DynamicExpressionStatement)) {
5252                                 args = new Arguments (0);
5253                                 prepared = true;
5254                                 source.Emit (ec);
5255                                 
5256                                 if (leave_copy) {
5257                                         ec.Emit (OpCodes.Dup);
5258                                         if (!IsStatic) {
5259                                                 temp = new LocalTemporary (this.Type);
5260                                                 temp.Store (ec);
5261                                         }
5262                                 }
5263                         } else {
5264                                 args = new Arguments (1);
5265
5266                                 if (leave_copy) {
5267                                         source.Emit (ec);
5268                                         temp = new LocalTemporary (this.Type);
5269                                         temp.Store (ec);
5270                                         args.Add (new Argument (temp));
5271                                 } else {
5272                                         args.Add (new Argument (source));
5273                                 }
5274                         }
5275
5276                         Invocation.EmitCall (ec, InstanceExpression, Setter, args, loc, false, prepared);
5277                         
5278                         if (temp != null) {
5279                                 temp.Emit (ec);
5280                                 temp.Release (ec);
5281                         }
5282                 }
5283
5284                 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
5285                 {
5286                         eclass = ExprClass.PropertyAccess;
5287
5288                         if (best_candidate.IsNotRealProperty) {
5289                                 Error_PropertyNotValid (rc);
5290                         }
5291
5292                         ResolveInstanceExpression (rc, right_side);
5293
5294                         if ((best_candidate.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0 && best_candidate.DeclaringType != InstanceExpression.Type) {
5295                                 var filter = new MemberFilter (best_candidate.Name, 0, MemberKind.Property, null, null);
5296                                 var p = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as PropertySpec;
5297                                 if (p != null) {
5298                                         type = p.MemberType;
5299                                 }
5300                         }
5301
5302                         DoBestMemberChecks (rc, best_candidate);
5303                         return this;
5304                 }
5305
5306                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
5307                 {
5308                         Error_TypeArgumentsCannotBeUsed (ec.Report, "property", GetSignatureForError (), loc);
5309                 }
5310         }
5311
5312         abstract class PropertyOrIndexerExpr<T> : MemberExpr, IDynamicAssign where T : PropertySpec
5313         {
5314                 // getter and setter can be different for base calls
5315                 MethodSpec getter, setter;
5316                 protected T best_candidate;
5317
5318                 protected LocalTemporary temp;
5319                 protected bool prepared;
5320
5321                 protected PropertyOrIndexerExpr (Location l)
5322                 {
5323                         loc = l;
5324                 }
5325
5326                 #region Properties
5327
5328                 public MethodSpec Getter {
5329                         get {
5330                                 return getter;
5331                         }
5332                         set {
5333                                 getter = value;
5334                         }
5335                 }
5336
5337                 public MethodSpec Setter {
5338                         get {
5339                                 return setter;
5340                         }
5341                         set {
5342                                 setter = value;
5343                         }
5344                 }
5345
5346                 #endregion
5347
5348                 protected override Expression DoResolve (ResolveContext ec)
5349                 {
5350                         if (eclass == ExprClass.Unresolved) {
5351                                 var expr = OverloadResolve (ec, null);
5352                                 if (expr == null)
5353                                         return null;
5354
5355                                 if (expr != this)
5356                                         return expr.Resolve (ec);
5357                         }
5358
5359                         if (!ResolveGetter (ec))
5360                                 return null;
5361
5362                         return this;
5363                 }
5364
5365                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5366                 {
5367                         if (right_side == EmptyExpression.OutAccess.Instance) {
5368                                 // TODO: best_candidate can be null at this point
5369                                 INamedBlockVariable variable = null;
5370                                 if (best_candidate != null && ec.CurrentBlock.ParametersBlock.TopBlock.GetLocalName (best_candidate.Name, ec.CurrentBlock, ref variable) && variable is Linq.RangeVariable) {
5371                                         ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
5372                                                 best_candidate.Name);
5373                                 } else {
5374                                         right_side.DoResolveLValue (ec, this);
5375                                 }
5376                                 return null;
5377                         }
5378
5379                         // if the property/indexer returns a value type, and we try to set a field in it
5380                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
5381                                 Error_CannotModifyIntermediateExpressionValue (ec);
5382                         }
5383
5384                         if (eclass == ExprClass.Unresolved) {
5385                                 var expr = OverloadResolve (ec, right_side);
5386                                 if (expr == null)
5387                                         return null;
5388
5389                                 if (expr != this)
5390                                         return expr.ResolveLValue (ec, right_side);
5391                         }
5392
5393                         if (!ResolveSetter (ec))
5394                                 return null;
5395
5396                         return this;
5397                 }
5398
5399                 //
5400                 // Implements the IAssignMethod interface for assignments
5401                 //
5402                 public abstract void Emit (EmitContext ec, bool leave_copy);
5403                 public abstract void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
5404
5405                 public override void Emit (EmitContext ec)
5406                 {
5407                         Emit (ec, false);
5408                 }
5409
5410                 public abstract SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source);
5411
5412                 protected abstract Expression OverloadResolve (ResolveContext rc, Expression right_side);
5413
5414                 bool ResolveGetter (ResolveContext rc)
5415                 {
5416                         if (!best_candidate.HasGet) {
5417                                 if (InstanceExpression != EmptyExpression.Null) {
5418                                         rc.Report.SymbolRelatedToPreviousError (best_candidate);
5419                                         rc.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
5420                                                 best_candidate.GetSignatureForError ());
5421                                         return false;
5422                                 }
5423                         } else if (!best_candidate.Get.IsAccessible (rc.CurrentType)) {
5424                                 if (best_candidate.HasDifferentAccessibility) {
5425                                         rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
5426                                         rc.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
5427                                                 TypeManager.CSharpSignature (best_candidate));
5428                                 } else {
5429                                         rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
5430                                         ErrorIsInaccesible (rc, best_candidate.Get.GetSignatureForError (), loc);
5431                                 }
5432                         }
5433
5434                         if (best_candidate.HasDifferentAccessibility) {
5435                                 CheckProtectedMemberAccess (rc, best_candidate.Get);
5436                         }
5437
5438                         getter = CandidateToBaseOverride (rc, best_candidate.Get);
5439                         return true;
5440                 }
5441
5442                 bool ResolveSetter (ResolveContext rc)
5443                 {
5444                         if (!best_candidate.HasSet) {
5445                                 rc.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read-only)",
5446                                         GetSignatureForError ());
5447                                 return false;
5448                         }
5449
5450                         if (!best_candidate.Set.IsAccessible (rc.CurrentType)) {
5451                                 if (best_candidate.HasDifferentAccessibility) {
5452                                         rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
5453                                         rc.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
5454                                                 GetSignatureForError ());
5455                                 } else {
5456                                         rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
5457                                         ErrorIsInaccesible (rc, best_candidate.Set.GetSignatureForError (), loc);
5458                                 }
5459                         }
5460
5461                         if (best_candidate.HasDifferentAccessibility)
5462                                 CheckProtectedMemberAccess (rc, best_candidate.Set);
5463
5464                         setter = CandidateToBaseOverride (rc, best_candidate.Set);
5465                         return true;
5466                 }
5467         }
5468
5469         /// <summary>
5470         ///   Fully resolved expression that evaluates to an Event
5471         /// </summary>
5472         public class EventExpr : MemberExpr, IAssignMethod
5473         {
5474                 readonly EventSpec spec;
5475                 MethodSpec op;
5476
5477                 public EventExpr (EventSpec spec, Location loc)
5478                 {
5479                         this.spec = spec;
5480                         this.loc = loc;
5481                 }
5482
5483                 #region Properties
5484
5485                 protected override TypeSpec DeclaringType {
5486                         get {
5487                                 return spec.DeclaringType;
5488                         }
5489                 }
5490
5491                 public override string Name {
5492                         get {
5493                                 return spec.Name;
5494                         }
5495                 }
5496
5497                 public override bool IsInstance {
5498                         get {
5499                                 return !spec.IsStatic;
5500                         }
5501                 }
5502
5503                 public override bool IsStatic {
5504                         get {
5505                                 return spec.IsStatic;
5506                         }
5507                 }
5508
5509                 public MethodSpec Operator {
5510                         get {
5511                                 return op;
5512                         }
5513                 }
5514
5515                 #endregion
5516
5517                 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
5518                 {
5519                         //
5520                         // If the event is local to this class and we are not lhs of +=/-= we transform ourselves into a FieldExpr
5521                         //
5522                         if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
5523                                 if (spec.BackingField != null &&
5524                                         (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType))) {
5525
5526                                         spec.MemberDefinition.SetIsUsed ();
5527
5528                                         if (!ec.IsObsolete) {
5529                                                 ObsoleteAttribute oa = spec.GetAttributeObsolete ();
5530                                                 if (oa != null)
5531                                                         AttributeTester.Report_ObsoleteMessage (oa, spec.GetSignatureForError (), loc, ec.Report);
5532                                         }
5533
5534                                         if ((spec.Modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
5535                                                 Error_AssignmentEventOnly (ec);
5536
5537                                         FieldExpr ml = new FieldExpr (spec.BackingField, loc);
5538
5539                                         InstanceExpression = null;
5540
5541                                         return ml.ResolveMemberAccess (ec, left, original);
5542                                 }
5543                         }
5544
5545                         return base.ResolveMemberAccess (ec, left, original);
5546                 }
5547
5548                 public override Expression CreateExpressionTree (ResolveContext ec)
5549                 {
5550                         throw new NotSupportedException ("ET");
5551                 }
5552
5553                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5554                 {
5555                         if (right_side == EmptyExpression.EventAddition) {
5556                                 op = spec.AccessorAdd;
5557                         } else if (right_side == EmptyExpression.EventSubtraction) {
5558                                 op = spec.AccessorRemove;
5559                         }
5560
5561                         if (op == null) {
5562                                 Error_AssignmentEventOnly (ec);
5563                                 return null;
5564                         }
5565
5566                         op = CandidateToBaseOverride (ec, op);
5567                         return this;
5568                 }
5569
5570                 protected override Expression DoResolve (ResolveContext ec)
5571                 {
5572                         eclass = ExprClass.EventAccess;
5573                         type = spec.MemberType;
5574
5575                         ResolveInstanceExpression (ec, null);
5576
5577                         if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
5578                                 Error_AssignmentEventOnly (ec);
5579                         }
5580
5581                         DoBestMemberChecks (ec, spec);
5582                         return this;
5583                 }               
5584
5585                 public override void Emit (EmitContext ec)
5586                 {
5587                         throw new NotSupportedException ();
5588                         //Error_CannotAssign ();
5589                 }
5590
5591                 #region IAssignMethod Members
5592
5593                 public void Emit (EmitContext ec, bool leave_copy)
5594                 {
5595                         throw new NotImplementedException ();
5596                 }
5597
5598                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5599                 {
5600                         if (leave_copy || !prepare_for_load)
5601                                 throw new NotImplementedException ("EventExpr::EmitAssign");
5602
5603                         Arguments args = new Arguments (1);
5604                         args.Add (new Argument (source));
5605                         Invocation.EmitCall (ec, InstanceExpression, op, args, loc);
5606                 }
5607
5608                 #endregion
5609
5610                 void Error_AssignmentEventOnly (ResolveContext ec)
5611                 {
5612                         if (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType)) {
5613                                 ec.Report.Error (79, loc,
5614                                         "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
5615                                         GetSignatureForError ());
5616                         } else {
5617                                 ec.Report.Error (70, loc,
5618                                         "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
5619                                         GetSignatureForError (), spec.DeclaringType.GetSignatureForError ());
5620                         }
5621                 }
5622
5623                 protected override void Error_CannotCallAbstractBase (ResolveContext rc, string name)
5624                 {
5625                         name = name.Substring (0, name.LastIndexOf ('.'));
5626                         base.Error_CannotCallAbstractBase (rc, name);
5627                 }
5628
5629                 public override string GetSignatureForError ()
5630                 {
5631                         return TypeManager.CSharpSignature (spec);
5632                 }
5633
5634                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
5635                 {
5636                         Error_TypeArgumentsCannotBeUsed (ec.Report, "event", GetSignatureForError (), loc);
5637                 }
5638         }
5639
5640         public class TemporaryVariableReference : VariableReference
5641         {
5642                 public class Declarator : Statement
5643                 {
5644                         TemporaryVariableReference variable;
5645
5646                         public Declarator (TemporaryVariableReference variable)
5647                         {
5648                                 this.variable = variable;
5649                                 loc = variable.loc;
5650                         }
5651
5652                         protected override void DoEmit (EmitContext ec)
5653                         {
5654                                 variable.li.CreateBuilder (ec);
5655                         }
5656
5657                         protected override void CloneTo (CloneContext clonectx, Statement target)
5658                         {
5659                                 // Nothing
5660                         }
5661                 }
5662
5663                 LocalVariable li;
5664
5665                 public TemporaryVariableReference (LocalVariable li, Location loc)
5666                 {
5667                         this.li = li;
5668                         this.type = li.Type;
5669                         this.loc = loc;
5670                 }
5671
5672                 public override bool IsLockedByStatement {
5673                         get {
5674                                 return false;
5675                         }
5676                         set {
5677                         }
5678                 }
5679
5680                 public LocalVariable LocalInfo {
5681                     get {
5682                         return li;
5683                     }
5684                 }
5685
5686                 public static TemporaryVariableReference Create (TypeSpec type, Block block, Location loc)
5687                 {
5688                         var li = LocalVariable.CreateCompilerGenerated (type, block, loc);
5689                         return new TemporaryVariableReference (li, loc);
5690                 }
5691
5692                 public override Expression CreateExpressionTree (ResolveContext ec)
5693                 {
5694                         throw new NotSupportedException ("ET");
5695                 }
5696
5697                 protected override Expression DoResolve (ResolveContext ec)
5698                 {
5699                         eclass = ExprClass.Variable;
5700
5701                         //
5702                         // Don't capture temporary variables except when using
5703                         // iterator redirection
5704                         //
5705                         if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.IsIterator && ec.IsVariableCapturingRequired) {
5706                                 AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
5707                                 storey.CaptureLocalVariable (ec, li);
5708                         }
5709
5710                         return this;
5711                 }
5712
5713                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5714                 {
5715                         return Resolve (ec);
5716                 }
5717                 
5718                 public override void Emit (EmitContext ec)
5719                 {
5720                         li.CreateBuilder (ec);
5721
5722                         Emit (ec, false);
5723                 }
5724
5725                 public void EmitAssign (EmitContext ec, Expression source)
5726                 {
5727                         li.CreateBuilder (ec);
5728
5729                         EmitAssign (ec, source, false, false);
5730                 }
5731
5732                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
5733                 {
5734                         return li.HoistedVariant;
5735                 }
5736
5737                 public override bool IsFixed {
5738                         get { return true; }
5739                 }
5740
5741                 public override bool IsRef {
5742                         get { return false; }
5743                 }
5744
5745                 public override string Name {
5746                         get { throw new NotImplementedException (); }
5747                 }
5748
5749                 public override void SetHasAddressTaken ()
5750                 {
5751                         throw new NotImplementedException ();
5752                 }
5753
5754                 protected override ILocalVariable Variable {
5755                         get { return li; }
5756                 }
5757
5758                 public override VariableInfo VariableInfo {
5759                         get { throw new NotImplementedException (); }
5760                 }
5761         }
5762
5763         /// 
5764         /// Handles `var' contextual keyword; var becomes a keyword only
5765         /// if no type called var exists in a variable scope
5766         /// 
5767         class VarExpr : SimpleName
5768         {
5769                 public VarExpr (Location loc)
5770                         : base ("var", loc)
5771                 {
5772                 }
5773
5774                 public bool InferType (ResolveContext ec, Expression right_side)
5775                 {
5776                         if (type != null)
5777                                 throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
5778                         
5779                         type = right_side.Type;
5780                         if (type == InternalType.Null || type == TypeManager.void_type || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
5781                                 ec.Report.Error (815, loc,
5782                                         "An implicitly typed local variable declaration cannot be initialized with `{0}'",
5783                                         type.GetSignatureForError ());
5784                                 return false;
5785                         }
5786
5787                         eclass = ExprClass.Variable;
5788                         return true;
5789                 }
5790
5791                 protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
5792                 {
5793                         if (RootContext.Version < LanguageVersion.V_3)
5794                                 base.Error_TypeOrNamespaceNotFound (ec);
5795                         else
5796                                 ec.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
5797                 }
5798         }
5799 }