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