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