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