BindingFlags.Public needed here as Exception.HResult is now public in .NET 4.5. This...
[mono.git] / mcs / mcs / anonymous.cs
1 //
2 // anonymous.cs: Support for anonymous methods and types
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximain.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
16 using System.Diagnostics;
17
18 #if STATIC
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using System.Reflection;
23 using System.Reflection.Emit;
24 #endif
25
26 namespace Mono.CSharp {
27
28         public abstract class CompilerGeneratedContainer : ClassOrStruct
29         {
30                 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
31                         : this (parent, name, mod, MemberKind.Class)
32                 {
33                 }
34
35                 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
36                         : base (parent, name, null, kind)
37                 {
38                         Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
39
40                         ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
41                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
42                 }
43
44                 protected void CheckMembersDefined ()
45                 {
46                         if (HasMembersDefined)
47                                 throw new InternalErrorException ("Helper class already defined!");
48                 }
49
50                 protected override bool DoDefineMembers ()
51                 {
52                         if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
53                                 DefineDefaultConstructor (false);
54                         }
55
56                         return base.DoDefineMembers ();
57                 }
58
59                 protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
60                 {
61                         string host_name = host == null ? null : host is InterfaceMemberBase ? ((InterfaceMemberBase)host).GetFullName (host.MemberName) : host.MemberName.Name;
62                         string tname = MakeName (host_name, "c", name, unique_id);
63                         TypeParameters args = null;
64                         if (tparams != null) {
65                                 args = new TypeParameters (tparams.Count);
66
67                                 // Type parameters will be filled later when we have TypeContainer
68                                 // instance, for now we need only correct arity to create valid name
69                                 for (int i = 0; i < tparams.Count; ++i)
70                                         args.Add ((TypeParameter) null);
71                         }
72
73                         return new MemberName (tname, args, loc);
74                 }
75
76                 public static string MakeName (string host, string typePrefix, string name, int id)
77                 {
78                         return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
79                 }
80
81                 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
82                 {
83                         base_type = Compiler.BuiltinTypes.Object;
84
85                         base_class = null;
86                         return null;
87                 }
88         }
89
90         public class HoistedStoreyClass : CompilerGeneratedContainer
91         {
92                 public sealed class HoistedField : Field
93                 {
94                         public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
95                                   Attributes attrs, Location loc)
96                                 : base (parent, type, mod, new MemberName (name, loc), attrs)
97                         {
98                         }
99
100                         protected override bool ResolveMemberType ()
101                         {
102                                 if (!base.ResolveMemberType ())
103                                         return false;
104
105                                 HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
106                                 if (parent != null && parent.Mutator != null)
107                                         member_type = parent.Mutator.Mutate (MemberType);
108
109                                 return true;
110                         }
111                 }
112
113                 protected TypeParameterMutator mutator;
114
115                 public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
116                         : base (parent, name, mods | Modifiers.PRIVATE, kind)
117                 {
118
119                         if (tparams != null) {
120                                 var type_params = name.TypeParameters;
121                                 var src = new TypeParameterSpec[tparams.Count];
122                                 var dst = new TypeParameterSpec[tparams.Count];
123
124                                 for (int i = 0; i < tparams.Count; ++i) {
125                                         type_params[i] = tparams[i].CreateHoistedCopy (spec);
126
127                                         src[i] = tparams[i].Type;
128                                         dst[i] = type_params[i].Type;
129                                 }
130
131                                 // A copy is not enough, inflate any type parameter constraints
132                                 // using a new type parameters
133                                 var inflator = new TypeParameterInflator (this, null, src, dst);
134                                 for (int i = 0; i < tparams.Count; ++i) {
135                                         src[i].InflateConstraints (inflator, dst[i]);
136                                 }
137
138                                 mutator = new TypeParameterMutator (tparams, type_params);
139                         }
140                 }
141
142                 #region Properties
143
144                 public TypeParameterMutator Mutator {
145                         get {
146                                 return mutator;
147                         }
148                         set {
149                                 mutator = value;
150                         }
151                 }
152
153                 #endregion
154
155                 public HoistedStoreyClass GetGenericStorey ()
156                 {
157                         TypeContainer storey = this;
158                         while (storey != null && storey.CurrentTypeParameters == null)
159                                 storey = storey.Parent;
160
161                         return storey as HoistedStoreyClass;
162                 }
163         }
164
165
166         //
167         // Anonymous method storey is created when an anonymous method uses
168         // variable or parameter from outer scope. They are then hoisted to
169         // anonymous method storey (captured)
170         //
171         public class AnonymousMethodStorey : HoistedStoreyClass
172         {
173                 struct StoreyFieldPair
174                 {
175                         public readonly AnonymousMethodStorey Storey;
176                         public readonly Field Field;
177
178                         public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
179                         {
180                                 this.Storey = storey;
181                                 this.Field = field;
182                         }
183                 }
184
185                 //
186                 // Needed to delay hoisted _this_ initialization. When an anonymous
187                 // method is used inside ctor and _this_ is hoisted, base ctor has to
188                 // be called first, otherwise _this_ will be initialized with 
189                 // uninitialized value.
190                 //
191                 sealed class ThisInitializer : Statement
192                 {
193                         readonly HoistedThis hoisted_this;
194
195                         public ThisInitializer (HoistedThis hoisted_this)
196                         {
197                                 this.hoisted_this = hoisted_this;
198                         }
199
200                         protected override void DoEmit (EmitContext ec)
201                         {
202                                 hoisted_this.EmitAssign (ec, new CompilerGeneratedThis (ec.CurrentType, loc), false, false);
203                         }
204
205                         protected override void CloneTo (CloneContext clonectx, Statement target)
206                         {
207                                 // Nothing to clone
208                         }
209                 }
210
211                 // Unique storey ID
212                 public readonly int ID;
213
214                 public readonly ExplicitBlock OriginalSourceBlock;
215
216                 // A list of StoreyFieldPair with local field keeping parent storey instance
217                 List<StoreyFieldPair> used_parent_storeys;
218                 List<ExplicitBlock> children_references;
219
220                 // A list of hoisted parameters
221                 protected List<HoistedParameter> hoisted_params;
222                 List<HoistedParameter> hoisted_local_params;
223                 protected List<HoistedVariable> hoisted_locals;
224
225                 // Hoisted this
226                 protected HoistedThis hoisted_this;
227
228                 // Local variable which holds this storey instance
229                 public Expression Instance;
230
231                 bool initialize_hoisted_this;
232
233                 public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
234                         : base (parent, MakeMemberName (host, name, parent.Module.CounterAnonymousContainers, tparams, block.StartLocation),
235                                 tparams, 0, kind)
236                 {
237                         OriginalSourceBlock = block;
238                         ID = parent.Module.CounterAnonymousContainers++;
239                 }
240
241                 public void AddCapturedThisField (EmitContext ec)
242                 {
243                         TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
244                         Field f = AddCompilerGeneratedField ("$this", type_expr);
245                         hoisted_this = new HoistedThis (this, f);
246
247                         initialize_hoisted_this = true;
248                 }
249
250                 public Field AddCapturedVariable (string name, TypeSpec type)
251                 {
252                         CheckMembersDefined ();
253
254                         FullNamedExpression field_type = new TypeExpression (type, Location);
255                         if (!spec.IsGenericOrParentIsGeneric)
256                                 return AddCompilerGeneratedField (name, field_type);
257
258                         const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
259                         Field f = new HoistedField (this, field_type, mod, name, null, Location);
260                         AddField (f);
261                         return f;
262                 }
263
264                 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
265                 {
266                         return AddCompilerGeneratedField (name, type, false);
267                 }
268
269                 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
270                 {
271                         Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
272                         Field f = new Field (this, type, mod, new MemberName (name, Location), null);
273                         AddField (f);
274                         return f;
275                 }
276
277                 //
278                 // Creates a link between hoisted variable block and the anonymous method storey
279                 //
280                 // An anonymous method can reference variables from any outer block, but they are
281                 // hoisted in their own ExplicitBlock. When more than one block is referenced we
282                 // need to create another link between those variable storeys
283                 //
284                 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
285                 {
286                         if (children_references == null)
287                                 children_references = new List<ExplicitBlock> ();
288
289                         if (!children_references.Contains (block))
290                                 children_references.Add (block);
291                 }
292
293                 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
294                 {
295                         CheckMembersDefined ();
296
297                         if (used_parent_storeys == null)
298                                 used_parent_storeys = new List<StoreyFieldPair> ();
299                         else if (used_parent_storeys.Exists (i => i.Storey == storey))
300                                 return;
301
302                         TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
303                         Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
304                         used_parent_storeys.Add (new StoreyFieldPair (storey, f));
305                 }
306
307                 public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
308                 {
309                         if (this is StateMachine) {
310                                 if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
311                                         ec.CurrentBlock.Explicit.HasCapturedVariable = true;
312                         } else {
313                                 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
314                         }
315
316                         var hoisted = localVariable.HoistedVariant;
317                         if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
318                                 // TODO: It's too late the field is defined in HoistedLocalVariable ctor
319                                 hoisted.Storey.hoisted_locals.Remove (hoisted);
320                                 hoisted = null;
321                         }
322
323                         if (hoisted == null) {
324                                 hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
325                                 localVariable.HoistedVariant = hoisted;
326
327                                 if (hoisted_locals == null)
328                                         hoisted_locals = new List<HoistedVariable> ();
329
330                                 hoisted_locals.Add (hoisted);
331                         }
332
333                         if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
334                                 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
335                 }
336
337                 public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
338                 {
339                         if (!(this is StateMachine)) {
340                                 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
341                         }
342
343                         var hoisted = parameterInfo.Parameter.HoistedVariant;
344
345                         if (parameterInfo.Block.StateMachine != null) {
346                                 //
347                                 // Another storey in same block exists but state machine does not
348                                 // have parameter captured. We need to add it there as well to
349                                 // proxy parameter value correctly.
350                                 //
351                                 if (hoisted == null && parameterInfo.Block.StateMachine != this) {
352                                         var storey = parameterInfo.Block.StateMachine;
353
354                                         hoisted = new HoistedParameter (storey, parameterReference);
355                                         parameterInfo.Parameter.HoistedVariant = hoisted;
356
357                                         if (storey.hoisted_params == null)
358                                                 storey.hoisted_params = new List<HoistedParameter> ();
359
360                                         storey.hoisted_params.Add (hoisted);
361                                 }
362
363                                 //
364                                 // Lift captured parameter from value type storey to reference type one. Otherwise
365                                 // any side effects would be done on a copy
366                                 //
367                                 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
368                                         if (hoisted_local_params == null)
369                                                 hoisted_local_params = new List<HoistedParameter> ();
370
371                                         hoisted_local_params.Add (hoisted);
372                                         hoisted = null;
373                                 }
374                         }
375
376                         if (hoisted == null) {
377                                 hoisted = new HoistedParameter (this, parameterReference);
378                                 parameterInfo.Parameter.HoistedVariant = hoisted;
379
380                                 if (hoisted_params == null)
381                                         hoisted_params = new List<HoistedParameter> ();
382
383                                 hoisted_params.Add (hoisted);
384                         }
385
386                         //
387                         // Register link between current block and parameter storey. It will
388                         // be used when setting up storey definition to deploy storey reference
389                         // when parameters are used from multiple blocks
390                         //
391                         if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
392                                 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
393                         }
394                 }
395
396                 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
397                 {
398                         //
399                         // Create an instance of storey type
400                         //
401                         TypeExpr storey_type_expr;
402                         if (CurrentTypeParameters != null) {
403                                 //
404                                 // Use current method type parameter (MVAR) for top level storey only. All
405                                 // nested storeys use class type parameter (VAR)
406                                 //
407                                 var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
408                                         ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
409                                         ec.CurrentTypeParameters;
410
411                                 TypeArguments targs = new TypeArguments ();
412
413                                 //
414                                 // Use type parameter name instead of resolved type parameter
415                                 // specification to resolve to correctly nested type parameters
416                                 //
417                                 for (int i = 0; i < tparams.Count; ++i)
418                                         targs.Add (new SimpleName (tparams [i].Name, Location)); //  new TypeParameterExpr (tparams[i], Location));
419
420                                 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
421                         } else {
422                                 storey_type_expr = new TypeExpression (CurrentType, Location);
423                         }
424
425                         return storey_type_expr;
426                 }
427
428                 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
429                 {
430                         Parent = parentStorey;
431                         spec.IsGeneric = false;
432                         spec.DeclaringType = parentStorey.CurrentType;
433                         MemberName.TypeParameters = null;
434                 }
435
436                 protected override bool DoResolveTypeParameters ()
437                 {
438                         // Although any storey can have type parameters they are all clones of method type
439                         // parameters therefore have to mutate MVAR references in any of cloned constraints
440                         if (CurrentTypeParameters != null) {
441                                 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
442                                         var spec = CurrentTypeParameters[i].Type;
443                                         spec.BaseType = mutator.Mutate (spec.BaseType);
444                                         if (spec.InterfacesDefined != null) {
445                                                 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
446                                                 for (int ii = 0; ii < mutated.Length; ++ii) {
447                                                         mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
448                                                 }
449
450                                                 spec.InterfacesDefined = mutated;
451                                         }
452
453                                         if (spec.TypeArguments != null) {
454                                                 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
455                                         }
456                                 }
457                         }
458
459                         //
460                         // Update parent cache as we most likely passed the point
461                         // where the cache was constructed
462                         //
463                         Parent.CurrentType.MemberCache.AddMember (this.spec);
464
465                         return true;
466                 }
467
468                 //
469                 // Initializes all hoisted variables
470                 //
471                 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
472                 {
473                         // There can be only one instance variable for each storey type
474                         if (Instance != null)
475                                 throw new InternalErrorException ();
476
477                         //
478                         // Create an instance of this storey
479                         //
480                         ResolveContext rc = new ResolveContext (ec.MemberContext);
481                         rc.CurrentBlock = block;
482
483                         var storey_type_expr = CreateStoreyTypeExpression (ec);
484                         var source = new New (storey_type_expr, null, Location).Resolve (rc);
485
486                         //
487                         // When the current context is async (or iterator) lift local storey
488                         // instantiation to the currect storey
489                         //
490                         if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
491                                 //
492                                 // Unfortunately, normal capture mechanism could not be used because we are
493                                 // too late in the pipeline and standart assign cannot be used either due to
494                                 // recursive nature of GetStoreyInstanceExpression
495                                 //
496                                 var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
497                                         LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
498
499                                 field.Define ();
500                                 field.Emit ();
501
502                                 var fexpr = new FieldExpr (field, Location);
503                                 fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
504                                 fexpr.EmitAssign (ec, source, false, false);
505                                 Instance = fexpr;
506                         } else {
507                                 var local = TemporaryVariableReference.Create (source.Type, block, Location);
508                                 if (source.Type.IsStruct) {
509                                         local.LocalInfo.CreateBuilder (ec);
510                                 } else {
511                                         local.EmitAssign (ec, source);
512                                 }
513
514                                 Instance = local;
515                         }
516
517                         EmitHoistedFieldsInitialization (rc, ec);
518
519                         // TODO: Implement properly
520                         //SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
521                 }
522
523                 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
524                 {
525                         //
526                         // Initialize all storey reference fields by using local or hoisted variables
527                         //
528                         if (used_parent_storeys != null) {
529                                 foreach (StoreyFieldPair sf in used_parent_storeys) {
530                                         //
531                                         // Get instance expression of storey field
532                                         //
533                                         Expression instace_expr = GetStoreyInstanceExpression (ec);
534                                         var fs = sf.Field.Spec;
535                                         if (TypeManager.IsGenericType (instace_expr.Type))
536                                                 fs = MemberCache.GetMember (instace_expr.Type, fs);
537
538                                         FieldExpr f_set_expr = new FieldExpr (fs, Location);
539                                         f_set_expr.InstanceExpression = instace_expr;
540
541                                         // TODO: CompilerAssign expression
542                                         SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
543                                         if (a.Resolve (rc) != null)
544                                                 a.EmitStatement (ec);
545                                 }
546                         }
547
548                         //
549                         // Initialize hoisted `this' only once, everywhere else will be
550                         // referenced indirectly
551                         //
552                         if (initialize_hoisted_this) {
553                                 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
554                         }
555
556                         //
557                         // Setting currect anonymous method to null blocks any further variable hoisting
558                         //
559                         AnonymousExpression ae = ec.CurrentAnonymousMethod;
560                         ec.CurrentAnonymousMethod = null;
561
562                         if (hoisted_params != null) {
563                                 EmitHoistedParameters (ec, hoisted_params);
564                         }
565
566                         ec.CurrentAnonymousMethod = ae;
567                 }
568
569                 protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
570                 {
571                         foreach (HoistedParameter hp in hoisted) {
572                                 //
573                                 // Parameters could be proxied via local fields for value type storey
574                                 //
575                                 if (hoisted_local_params != null) {
576                                         var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
577                                         var source = new FieldExpr (local_param.Field, Location);
578                                         source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
579                                         hp.EmitAssign (ec, source, false, false);
580                                         continue;
581                                 }
582
583                                 hp.EmitHoistingAssignment (ec);
584                         }
585                 }
586
587                 //
588                 // Returns a field which holds referenced storey instance
589                 //
590                 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
591                 {
592                         if (used_parent_storeys == null)
593                                 return null;
594
595                         foreach (StoreyFieldPair sf in used_parent_storeys) {
596                                 if (sf.Storey == storey)
597                                         return sf.Field;
598                         }
599
600                         return null;
601                 }
602
603                 //
604                 // Creates storey instance expression regardless of currect IP
605                 //
606                 public Expression GetStoreyInstanceExpression (EmitContext ec)
607                 {
608                         AnonymousExpression am = ec.CurrentAnonymousMethod;
609
610                         //
611                         // Access from original block -> storey
612                         //
613                         if (am == null)
614                                 return Instance;
615
616                         //
617                         // Access from anonymous method implemented as a static -> storey
618                         //
619                         if (am.Storey == null)
620                                 return Instance;
621
622                         Field f = am.Storey.GetReferencedStoreyField (this);
623                         if (f == null) {
624                                 if (am.Storey == this) {
625                                         //
626                                         // Access from inside of same storey (S -> S)
627                                         //
628                                         return new CompilerGeneratedThis (CurrentType, Location);
629                                 }
630
631                                 //
632                                 // External field access
633                                 //
634                                 return Instance;
635                         }
636
637                         //
638                         // Storey was cached to local field
639                         //
640                         FieldExpr f_ind = new FieldExpr (f, Location);
641                         f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
642                         return f_ind;
643                 }
644
645                 protected virtual string GetVariableMangledName (LocalVariable local_info)
646                 {
647                         //
648                         // No need to mangle anonymous method hoisted variables cause they
649                         // are hoisted in their own scopes
650                         //
651                         return local_info.Name;
652                 }
653
654                 public HoistedThis HoistedThis {
655                         get {
656                                 return hoisted_this;
657                         }
658                         set {
659                                 hoisted_this = value;
660                         }
661                 }
662
663                 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
664                         get { return children_references; }
665                 }
666         }
667
668         public abstract class HoistedVariable
669         {
670                 //
671                 // Hoisted version of variable references used in expression
672                 // tree has to be delayed until we know its location. The variable
673                 // doesn't know its location until all stories are calculated
674                 //
675                 class ExpressionTreeVariableReference : Expression
676                 {
677                         readonly HoistedVariable hv;
678
679                         public ExpressionTreeVariableReference (HoistedVariable hv)
680                         {
681                                 this.hv = hv;
682                         }
683
684                         public override bool ContainsEmitWithAwait ()
685                         {
686                                 return false;
687                         }
688
689                         public override Expression CreateExpressionTree (ResolveContext ec)
690                         {
691                                 return hv.CreateExpressionTree ();
692                         }
693
694                         protected override Expression DoResolve (ResolveContext ec)
695                         {
696                                 eclass = ExprClass.Value;
697                                 type = ec.Module.PredefinedTypes.Expression.Resolve ();
698                                 return this;
699                         }
700
701                         public override void Emit (EmitContext ec)
702                         {
703                                 ResolveContext rc = new ResolveContext (ec.MemberContext);
704                                 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
705                                 // This should never fail
706                                 e = e.Resolve (rc);
707                                 if (e != null)
708                                         e.Emit (ec);
709                         }
710                 }
711         
712                 protected readonly AnonymousMethodStorey storey;
713                 protected Field field;
714                 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
715                 FieldExpr cached_outer_access;
716
717                 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
718                         : this (storey, storey.AddCapturedVariable (name, type))
719                 {
720                 }
721
722                 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
723                 {
724                         this.storey = storey;
725                         this.field = field;
726                 }
727
728                 public AnonymousMethodStorey Storey {
729                         get {
730                                 return storey;
731                         }
732                 }
733
734                 public void AddressOf (EmitContext ec, AddressOp mode)
735                 {
736                         GetFieldExpression (ec).AddressOf (ec, mode);
737                 }
738
739                 public Expression CreateExpressionTree ()
740                 {
741                         return new ExpressionTreeVariableReference (this);
742                 }
743
744                 public void Emit (EmitContext ec)
745                 {
746                         GetFieldExpression (ec).Emit (ec);
747                 }
748
749                 public Expression EmitToField (EmitContext ec)
750                 {
751                         return GetFieldExpression (ec);
752                 }
753
754                 //
755                 // Creates field access expression for hoisted variable
756                 //
757                 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
758                 {
759                         if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
760                                 if (cached_outer_access != null)
761                                         return cached_outer_access;
762
763                                 //
764                                 // When setting top-level hoisted variable in generic storey
765                                 // change storey generic types to method generic types (VAR -> MVAR)
766                                 //
767                                 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
768                                         var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
769                                         cached_outer_access = new FieldExpr (fs, field.Location);
770                                 } else {
771                                         cached_outer_access = new FieldExpr (field, field.Location);
772                                 }
773
774                                 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
775                                 return cached_outer_access;
776                         }
777
778                         FieldExpr inner_access;
779                         if (cached_inner_access != null) {
780                                 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
781                                         inner_access = null;
782                         } else {
783                                 inner_access = null;
784                                 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
785                         }
786
787                         if (inner_access == null) {
788                                 if (field.Parent.IsGenericOrParentIsGeneric) {
789                                         var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
790                                         inner_access = new FieldExpr (fs, field.Location);
791                                 } else {
792                                         inner_access = new FieldExpr (field, field.Location);
793                                 }
794
795                                 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
796                                 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
797                         }
798
799                         return inner_access;
800                 }
801
802                 public void Emit (EmitContext ec, bool leave_copy)
803                 {
804                         GetFieldExpression (ec).Emit (ec, leave_copy);
805                 }
806
807                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
808                 {
809                         GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
810                 }
811         }
812
813         public class HoistedParameter : HoistedVariable
814         {
815                 sealed class HoistedFieldAssign : CompilerAssign
816                 {
817                         public HoistedFieldAssign (Expression target, Expression source)
818                                 : base (target, source, source.Location)
819                         {
820                         }
821
822                         protected override Expression ResolveConversions (ResolveContext ec)
823                         {
824                                 //
825                                 // Implicit conversion check fails for hoisted type arguments
826                                 // as they are of different types (!!0 x !0)
827                                 //
828                                 return this;
829                         }
830                 }
831
832                 readonly ParameterReference parameter;
833
834                 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
835                         : base (scope, par.Name, par.Type)
836                 {
837                         this.parameter = par;
838                 }
839
840                 public HoistedParameter (HoistedParameter hp, string name)
841                         : base (hp.storey, name, hp.parameter.Type)
842                 {
843                         this.parameter = hp.parameter;
844                 }
845
846                 #region Properties
847
848                 public Field Field {
849                         get {
850                                 return field;
851                         }
852                 }
853
854                 public ParameterReference Parameter {
855                         get {
856                                 return parameter;
857                         }
858                 }
859
860                 #endregion
861
862                 public void EmitHoistingAssignment (EmitContext ec)
863                 {
864                         //
865                         // Remove hoisted redirection to emit assignment from original parameter
866                         //
867                         var temp = parameter.Parameter.HoistedVariant;
868                         parameter.Parameter.HoistedVariant = null;
869
870                         var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
871                         a.EmitStatement (ec);
872
873                         parameter.Parameter.HoistedVariant = temp;
874                 }
875         }
876
877         class HoistedLocalVariable : HoistedVariable
878         {
879                 public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
880                         : base (storey, name, local.Type)
881                 {
882                 }
883         }
884
885         public class HoistedThis : HoistedVariable
886         {
887                 public HoistedThis (AnonymousMethodStorey storey, Field field)
888                         : base (storey, field)
889                 {
890                 }
891
892                 public Field Field {
893                         get {
894                                 return field;
895                         }
896                 }
897         }
898
899         //
900         // Anonymous method expression as created by parser
901         //
902         public class AnonymousMethodExpression : Expression
903         {
904                 //
905                 // Special conversion for nested expression tree lambdas
906                 //
907                 class Quote : ShimExpression
908                 {
909                         public Quote (Expression expr)
910                                 : base (expr)
911                         {
912                         }
913
914                         public override Expression CreateExpressionTree (ResolveContext ec)
915                         {
916                                 var args = new Arguments (1);
917                                 args.Add (new Argument (expr.CreateExpressionTree (ec)));
918                                 return CreateExpressionFactoryCall (ec, "Quote", args);
919                         }
920
921                         protected override Expression DoResolve (ResolveContext rc)
922                         {
923                                 expr = expr.Resolve (rc);
924                                 if (expr == null)
925                                         return null;
926
927                                 eclass = expr.eclass;
928                                 type = expr.Type;
929                                 return this;
930                         }
931                 }
932
933                 readonly Dictionary<TypeSpec, Expression> compatibles;
934
935                 public ParametersBlock Block;
936
937                 public AnonymousMethodExpression (Location loc)
938                 {
939                         this.loc = loc;
940                         this.compatibles = new Dictionary<TypeSpec, Expression> ();
941                 }
942
943                 #region Properties
944
945                 public override string ExprClassName {
946                         get {
947                                 return "anonymous method";
948                         }
949                 }
950
951                 public virtual bool HasExplicitParameters {
952                         get {
953                                 return Parameters != ParametersCompiled.Undefined;
954                         }
955                 }
956
957                 public ParametersCompiled Parameters {
958                         get {
959                                 return Block.Parameters;
960                         }
961                 }
962
963                 public ReportPrinter TypeInferenceReportPrinter {
964                         get; set;
965                 }
966
967                 #endregion
968
969                 //
970                 // Returns true if the body of lambda expression can be implicitly
971                 // converted to the delegate of type `delegate_type'
972                 //
973                 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
974                 {
975                         using (ec.With (ResolveContext.Options.InferReturnType, false)) {
976                                 using (ec.Set (ResolveContext.Options.ProbingMode)) {
977                                         var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
978
979                                         var res = Compatible (ec, delegate_type) != null;
980
981                                         ec.Report.SetPrinter (prev);
982
983                                         return res;
984                                 }
985                         }
986                 }
987
988                 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
989                 {
990                         if (delegate_type.IsDelegate)
991                                 return delegate_type;
992
993                         if (delegate_type.IsExpressionTreeType) {
994                                 delegate_type = delegate_type.TypeArguments [0];
995                                 if (delegate_type.IsDelegate)
996                                         return delegate_type;
997
998                                 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
999                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1000                                 return null;
1001                         }
1002
1003                         ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1004                                       GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1005                         return null;
1006                 }
1007
1008                 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
1009                 {
1010                         if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
1011                                 return true;
1012
1013                         if (!ec.IsInProbingMode)
1014                                 ec.Report.Error (1661, loc,
1015                                         "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1016                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
1017
1018                         return false;
1019                 }
1020
1021                 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
1022                 {
1023                         if (Parameters.Count != invoke_pd.Count) {
1024                                 if (ignore_errors)
1025                                         return false;
1026                                 
1027                                 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1028                                               TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
1029                                 return false;
1030                         }
1031
1032                         bool has_implicit_parameters = !HasExplicitParameters;
1033                         bool error = false;
1034
1035                         for (int i = 0; i < Parameters.Count; ++i) {
1036                                 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
1037                                 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1038                                         if (ignore_errors)
1039                                                 return false;
1040                                         
1041                                         if (p_mod == Parameter.Modifier.NONE)
1042                                                 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
1043                                                               (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
1044                                         else
1045                                                 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
1046                                                               (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1047                                         error = true;
1048                                 }
1049
1050                                 if (has_implicit_parameters)
1051                                         continue;
1052
1053                                 TypeSpec type = invoke_pd.Types [i];
1054                                 
1055                                 // We assume that generic parameters are always inflated
1056                                 if (TypeManager.IsGenericParameter (type))
1057                                         continue;
1058                                 
1059                                 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
1060                                         continue;
1061                                 
1062                                 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
1063                                         if (ignore_errors)
1064                                                 return false;
1065                                         
1066                                         ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1067                                                       (i+1).ToString (),
1068                                                       TypeManager.CSharpName (Parameters.Types [i]),
1069                                                       TypeManager.CSharpName (invoke_pd.Types [i]));
1070                                         error = true;
1071                                 }
1072                         }
1073
1074                         return !error;
1075                 }
1076
1077                 //
1078                 // Infers type arguments based on explicit arguments
1079                 //
1080                 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
1081                 {
1082                         if (!HasExplicitParameters)
1083                                 return false;
1084
1085                         if (!delegate_type.IsDelegate) {
1086                                 if (!delegate_type.IsExpressionTreeType)
1087                                         return false;
1088
1089                                 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1090                                 if (!delegate_type.IsDelegate)
1091                                         return false;
1092                         }
1093                         
1094                         AParametersCollection d_params = Delegate.GetParameters (delegate_type);
1095                         if (d_params.Count != Parameters.Count)
1096                                 return false;
1097
1098                         for (int i = 0; i < Parameters.Count; ++i) {
1099                                 if (type_inference.ExactInference (Parameters.Types[i], d_params.Types[i]) == 0)
1100                                         return false;
1101                         }
1102
1103                         return true;
1104                 }
1105
1106                 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1107                 {
1108                         Expression expr;
1109                         AnonymousExpression am;
1110
1111                         if (compatibles.TryGetValue (delegate_type, out expr)) {
1112                                 am = expr as AnonymousExpression;
1113                                 return am == null ? null : am.ReturnType;
1114                         }
1115
1116                         using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1117                                 ReportPrinter prev;
1118                                 if (TypeInferenceReportPrinter != null) {
1119                                         prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
1120                                 } else {
1121                                         prev = null;
1122                                 }
1123
1124                                 var body = CompatibleMethodBody (ec, tic, null, delegate_type);
1125                                 if (body != null) {
1126                                         am = body.Compatible (ec, body);
1127                                 } else {
1128                                         am = null;
1129                                 }
1130
1131                                 if (TypeInferenceReportPrinter != null) {
1132                                         ec.Report.SetPrinter (prev);
1133                                 }
1134                         }
1135
1136                         if (am == null)
1137                                 return null;
1138
1139 //                      compatibles.Add (delegate_type, am);
1140                         return am.ReturnType;
1141                 }
1142
1143                 public override bool ContainsEmitWithAwait ()
1144                 {
1145                         return false;
1146                 }
1147
1148                 //
1149                 // Returns AnonymousMethod container if this anonymous method
1150                 // expression can be implicitly converted to the delegate type `delegate_type'
1151                 //
1152                 public Expression Compatible (ResolveContext ec, TypeSpec type)
1153                 {
1154                         Expression am;
1155                         if (compatibles.TryGetValue (type, out am))
1156                                 return am;
1157
1158                         TypeSpec delegate_type = CompatibleChecks (ec, type);
1159                         if (delegate_type == null)
1160                                 return null;
1161
1162                         //
1163                         // At this point its the first time we know the return type that is 
1164                         // needed for the anonymous method.  We create the method here.
1165                         //
1166
1167                         var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
1168                         TypeSpec return_type = invoke_mb.ReturnType;
1169
1170                         //
1171                         // Second: the return type of the delegate must be compatible with 
1172                         // the anonymous type.   Instead of doing a pass to examine the block
1173                         // we satisfy the rule by setting the return type on the EmitContext
1174                         // to be the delegate type return type.
1175                         //
1176
1177                         var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1178                         if (body == null)
1179                                 return null;
1180
1181                         bool etree_conversion = delegate_type != type;
1182
1183                         try {
1184                                 if (etree_conversion) {
1185                                         if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1186                                                 //
1187                                                 // Nested expression tree lambda use same scope as parent
1188                                                 // lambda, this also means no variable capturing between this
1189                                                 // and parent scope
1190                                                 //
1191                                                 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1192
1193                                                 //
1194                                                 // Quote nested expression tree
1195                                                 //
1196                                                 if (am != null)
1197                                                         am = new Quote (am);
1198                                         } else {
1199                                                 int errors = ec.Report.Errors;
1200
1201                                                 if (Block.IsAsync) {
1202                                                         ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
1203                                                 }
1204
1205                                                 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1206                                                         am = body.Compatible (ec);
1207                                                 }
1208
1209                                                 //
1210                                                 // Rewrite expressions into expression tree when targeting Expression<T>
1211                                                 //
1212                                                 if (am != null && errors == ec.Report.Errors)
1213                                                         am = CreateExpressionTree (ec, delegate_type);
1214                                         }
1215                                 } else {
1216                                         am = body.Compatible (ec);
1217                                 }
1218                         } catch (CompletionResult) {
1219                                 throw;
1220                         } catch (FatalException) {
1221                                 throw;
1222                         } catch (Exception e) {
1223                                 throw new InternalErrorException (e, loc);
1224                         }
1225
1226                         if (!ec.IsInProbingMode) {
1227                                 compatibles.Add (type, am ?? EmptyExpression.Null);
1228                         }
1229
1230                         return am;
1231                 }
1232
1233                 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1234                 {
1235                         return CreateExpressionTree (ec);
1236                 }
1237
1238                 public override Expression CreateExpressionTree (ResolveContext ec)
1239                 {
1240                         ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1241                         return null;
1242                 }
1243
1244                 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1245                 {
1246                         var delegate_parameters = Delegate.GetParameters (delegate_type);
1247
1248                         if (Parameters == ParametersCompiled.Undefined) {
1249                                 //
1250                                 // We provide a set of inaccessible parameters
1251                                 //
1252                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1253
1254                                 for (int i = 0; i < delegate_parameters.Count; i++) {
1255                                         Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1256                                         if ((i_mod & Parameter.Modifier.OUT) != 0) {
1257                                                 if (!ec.IsInProbingMode) {
1258                                                         ec.Report.Error (1688, loc,
1259                                                                 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1260                                                                 delegate_type.GetSignatureForError ());
1261                                                 }
1262
1263                                                 return null;
1264                                         }
1265                                         fixedpars[i] = new Parameter (
1266                                                 new TypeExpression (delegate_parameters.Types [i], loc), null,
1267                                                 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1268                                 }
1269
1270                                 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1271                         }
1272
1273                         if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1274                                 return null;
1275                         }
1276
1277                         return Parameters;
1278                 }
1279
1280                 protected override Expression DoResolve (ResolveContext ec)
1281                 {
1282                         if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1283                                 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1284                                 return null;
1285                         }
1286
1287                         //
1288                         // Set class type, set type
1289                         //
1290
1291                         eclass = ExprClass.Value;
1292
1293                         //
1294                         // This hack means `The type is not accessible
1295                         // anywhere', we depend on special conversion
1296                         // rules.
1297                         // 
1298                         type = InternalType.AnonymousMethod;
1299
1300                         if (!DoResolveParameters (ec))
1301                                 return null;
1302
1303 #if !STATIC
1304                         // FIXME: The emitted code isn't very careful about reachability
1305                         // so, ensure we have a 'ret' at the end
1306                         BlockContext bc = ec as BlockContext;
1307                         if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1308                                 bc.NeedReturnLabel ();
1309 #endif
1310                         return this;
1311                 }
1312
1313                 protected virtual bool DoResolveParameters (ResolveContext rc)
1314                 {
1315                         return Parameters.Resolve (rc);
1316                 }
1317
1318                 public override void Emit (EmitContext ec)
1319                 {
1320                         // nothing, as we only exist to not do anything.
1321                 }
1322
1323                 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1324                 {
1325                         ec.Report.Error (1686, loc,
1326                                 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
1327                                 var.Name);
1328                 }
1329
1330                 public override string GetSignatureForError ()
1331                 {
1332                         return ExprClassName;
1333                 }
1334
1335                 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1336                 {
1337                         ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1338                         if (p == null)
1339                                 return null;
1340
1341                         ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1342
1343                         if (b.IsAsync) {
1344                                 var rt = return_type;
1345                                 if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
1346                                         ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
1347                                                 GetSignatureForError (), delegate_type.GetSignatureForError ());
1348
1349                                         return null;
1350                                 }
1351
1352                                 b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, loc);
1353                         }
1354
1355                         return CompatibleMethodFactory (return_type ?? InternalType.Arglist, delegate_type, p, b);
1356                 }
1357
1358                 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1359                 {
1360                         return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1361                 }
1362
1363                 protected override void CloneTo (CloneContext clonectx, Expression t)
1364                 {
1365                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1366
1367                         target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1368                 }
1369                 
1370                 public override object Accept (StructuralVisitor visitor)
1371                 {
1372                         return visitor.Visit (this);
1373                 }
1374         }
1375
1376         //
1377         // Abstract expression for any block which requires variables hoisting
1378         //
1379         public abstract class AnonymousExpression : ExpressionStatement
1380         {
1381                 protected class AnonymousMethodMethod : Method
1382                 {
1383                         public readonly AnonymousExpression AnonymousMethod;
1384                         public readonly AnonymousMethodStorey Storey;
1385
1386                         public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
1387                                                           TypeExpr return_type,
1388                                                           Modifiers mod, MemberName name,
1389                                                           ParametersCompiled parameters)
1390                                 : base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
1391                                                 name, parameters, null)
1392                         {
1393                                 this.AnonymousMethod = am;
1394                                 this.Storey = storey;
1395
1396                                 Parent.PartialContainer.Members.Add (this);
1397                                 Block = new ToplevelBlock (am.block, parameters);
1398                         }
1399
1400                         public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1401                         {
1402                                 EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
1403                                 ec.CurrentAnonymousMethod = AnonymousMethod;
1404                                 return ec;
1405                         }
1406
1407                         protected override void DefineTypeParameters ()
1408                         {
1409                                 // Type parameters were cloned
1410                         }
1411
1412                         protected override bool ResolveMemberType ()
1413                         {
1414                                 if (!base.ResolveMemberType ())
1415                                         return false;
1416
1417                                 if (Storey != null && Storey.Mutator != null) {
1418                                         if (!parameters.IsEmpty) {
1419                                                 var mutated = Storey.Mutator.Mutate (parameters.Types);
1420                                                 if (mutated != parameters.Types)
1421                                                         parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1422                                         }
1423
1424                                         member_type = Storey.Mutator.Mutate (member_type);
1425                                 }
1426
1427                                 return true;
1428                         }
1429
1430                         public override void Emit ()
1431                         {
1432                                 if (MethodBuilder == null) {
1433                                         Define ();
1434                                 }
1435
1436                                 base.Emit ();
1437                         }
1438                 }
1439
1440                 protected ParametersBlock block;
1441
1442                 public TypeSpec ReturnType;
1443
1444                 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1445                 {
1446                         this.ReturnType = return_type;
1447                         this.block = block;
1448                         this.loc = loc;
1449                 }
1450
1451                 public abstract string ContainerType { get; }
1452                 public abstract bool IsIterator { get; }
1453                 public abstract AnonymousMethodStorey Storey { get; }
1454
1455                 //
1456                 // The block that makes up the body for the anonymous method
1457                 //
1458                 public ParametersBlock Block {
1459                         get {
1460                                 return block;
1461                         }
1462                 }
1463
1464                 public AnonymousExpression Compatible (ResolveContext ec)
1465                 {
1466                         return Compatible (ec, this);
1467                 }
1468
1469                 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1470                 {
1471                         if (block.Resolved)
1472                                 return this;
1473
1474                         // TODO: Implement clone
1475                         BlockContext aec = new BlockContext (ec, block, ReturnType);
1476                         aec.CurrentAnonymousMethod = ae;
1477
1478                         ResolveContext.Options flags = 0;
1479
1480                         var am = this as AnonymousMethodBody;
1481
1482                         if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1483                                 am.ReturnTypeInference = new TypeInferenceContext ();
1484                         }
1485
1486                         if (ec.IsInProbingMode)
1487                                 flags |= ResolveContext.Options.ProbingMode;
1488
1489                         if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1490                                 flags |= ResolveContext.Options.FieldInitializerScope;
1491
1492                         if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1493                                 flags |= ResolveContext.Options.ExpressionTreeConversion;
1494
1495                         aec.Set (flags);
1496
1497                         var errors = ec.Report.Errors;
1498
1499                         bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1500
1501                         if (am != null && am.ReturnTypeInference != null) {
1502                                 am.ReturnTypeInference.FixAllTypes (ec);
1503                                 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1504                                 am.ReturnTypeInference = null;
1505
1506                                 //
1507                                 // If e is synchronous the inferred return type is T
1508                                 // If e is asynchronous the inferred return type is Task<T>
1509                                 //
1510                                 if (block.IsAsync && ReturnType != null) {
1511                                         ReturnType = ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
1512                                 }
1513                         }
1514
1515                         if (res && errors != ec.Report.Errors)
1516                                 return null;
1517
1518                         return res ? this : null;
1519                 }
1520
1521                 public override bool ContainsEmitWithAwait ()
1522                 {
1523                         return false;
1524                 }
1525
1526                 public void SetHasThisAccess ()
1527                 {
1528                         ExplicitBlock b = block;
1529                         do {
1530                                 if (b.HasCapturedThis)
1531                                         return;
1532
1533                                 b.HasCapturedThis = true;
1534                                 b = b.Parent == null ? null : b.Parent.Explicit;
1535                         } while (b != null);
1536                 }
1537         }
1538
1539         public class AnonymousMethodBody : AnonymousExpression
1540         {
1541                 protected readonly ParametersCompiled parameters;
1542                 AnonymousMethodStorey storey;
1543
1544                 AnonymousMethodMethod method;
1545                 Field am_cache;
1546                 string block_name;
1547                 TypeInferenceContext return_inference;
1548
1549                 public AnonymousMethodBody (ParametersCompiled parameters,
1550                                         ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1551                                         Location loc)
1552                         : base (block, return_type, loc)
1553                 {
1554                         this.type = delegate_type;
1555                         this.parameters = parameters;
1556                 }
1557
1558                 #region Properties
1559
1560                 public override string ContainerType {
1561                         get { return "anonymous method"; }
1562                 }
1563
1564                 public override bool IsIterator {
1565                         get {
1566                                 return false;
1567                         }
1568                 }
1569
1570                 public ParametersCompiled Parameters {
1571                         get {
1572                                 return parameters;
1573                         }
1574                 }
1575
1576                 public TypeInferenceContext ReturnTypeInference {
1577                         get {
1578                                 return return_inference;
1579                         }
1580                         set {
1581                                 return_inference = value;
1582                         }
1583                 }
1584
1585                 public override AnonymousMethodStorey Storey {
1586                         get { return storey; }
1587                 }
1588
1589                 #endregion
1590
1591                 public override Expression CreateExpressionTree (ResolveContext ec)
1592                 {
1593                         ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1594                         return null;
1595                 }
1596
1597                 bool Define (ResolveContext ec)
1598                 {
1599                         if (!Block.Resolved && Compatible (ec) == null)
1600                                 return false;
1601
1602                         if (block_name == null) {
1603                                 MemberCore mc = (MemberCore) ec.MemberContext;
1604                                 block_name = mc.MemberName.Basename;
1605                         }
1606
1607                         return true;
1608                 }
1609
1610                 //
1611                 // Creates a host for the anonymous method
1612                 //
1613                 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1614                 {
1615                         //
1616                         // Anonymous method body can be converted to
1617                         //
1618                         // 1, an instance method in current scope when only `this' is hoisted
1619                         // 2, a static method in current scope when neither `this' nor any variable is hoisted
1620                         // 3, an instance method in compiler generated storey when any hoisted variable exists
1621                         //
1622
1623                         Modifiers modifiers;
1624                         TypeDefinition parent = null;
1625
1626                         var src_block = Block.Original.Explicit;
1627                         if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
1628                                 parent = storey = FindBestMethodStorey ();
1629
1630                                 if (storey == null) {
1631                                         var sm = src_block.ParametersBlock.TopBlock.StateMachine;
1632
1633                                         //
1634                                         // Remove hoisted this demand when simple instance method is enough
1635                                         //
1636                                         if (src_block.HasCapturedThis) {
1637                                                 src_block.ParametersBlock.TopBlock.RemoveThisReferenceFromChildrenBlock (src_block);
1638
1639                                                 //
1640                                                 // Special case where parent class is used to emit instance method
1641                                                 // because currect storey is of value type (async host) and we don't
1642                                                 // want to create another childer storey to host this reference only
1643                                                 //
1644                                                 if (sm != null && sm.Kind == MemberKind.Struct)
1645                                                         parent = sm.Parent.PartialContainer;
1646                                         }
1647
1648                                         //
1649                                         // For iterators we can host everything in one class
1650                                         //
1651                                         if (sm is IteratorStorey)
1652                                                 parent = storey = sm;
1653                                 }
1654
1655                                 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1656                         } else {
1657                                 if (ec.CurrentAnonymousMethod != null)
1658                                         parent = storey = ec.CurrentAnonymousMethod.Storey;
1659
1660                                 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1661                         }
1662
1663                         if (parent == null)
1664                                 parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
1665
1666                         string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
1667                                 "m", null, ec.Module.CounterAnonymousMethods++);
1668
1669                         MemberName member_name;
1670                         if (storey == null && ec.CurrentTypeParameters != null) {
1671
1672                                 var hoisted_tparams = ec.CurrentTypeParameters;
1673                                 var type_params = new TypeParameters (hoisted_tparams.Count);
1674                                 for (int i = 0; i < hoisted_tparams.Count; ++i) {
1675                                     type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
1676                                 }
1677
1678                                 member_name = new MemberName (name, type_params, Location);
1679                         } else {
1680                                 member_name = new MemberName (name, Location);
1681                         }
1682
1683                         return new AnonymousMethodMethod (parent,
1684                                 this, storey, new TypeExpression (ReturnType, Location), modifiers,
1685                                 member_name, parameters);
1686                 }
1687
1688                 protected override Expression DoResolve (ResolveContext ec)
1689                 {
1690                         if (!Define (ec))
1691                                 return null;
1692
1693                         eclass = ExprClass.Value;
1694                         return this;
1695                 }
1696
1697                 public override void Emit (EmitContext ec)
1698                 {
1699                         //
1700                         // Use same anonymous method implementation for scenarios where same
1701                         // code is used from multiple blocks, e.g. field initializers
1702                         //
1703                         if (method == null) {
1704                                 //
1705                                 // Delay an anonymous method definition to avoid emitting unused code
1706                                 // for unreachable blocks or expression trees
1707                                 //
1708                                 method = DoCreateMethodHost (ec);
1709                                 method.Define ();
1710                         }
1711
1712                         bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1713                         if (is_static && am_cache == null) {
1714                                 //
1715                                 // Creates a field cache to store delegate instance if it's not generic
1716                                 //
1717                                 if (!method.MemberName.IsGeneric) {
1718                                         var parent = method.Parent.PartialContainer;
1719                                         int id = parent.AnonymousMethodsCounter++;
1720                                         var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1721
1722                                         am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1723                                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1724                                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
1725                                         am_cache.Define ();
1726                                         parent.AddField (am_cache);
1727                                 } else {
1728                                         // TODO: Implement caching of generated generic static methods
1729                                         //
1730                                         // Idea:
1731                                         //
1732                                         // Some extra class is needed to capture variable generic type
1733                                         // arguments. Maybe we could re-use anonymous types, with a unique
1734                                         // anonymous method id, but they are quite heavy.
1735                                         //
1736                                         // Consider : "() => typeof(T);"
1737                                         //
1738                                         // We need something like
1739                                         // static class Wrap<Tn, Tm, DelegateType> {
1740                                         //              public static DelegateType cache;
1741                                         // }
1742                                         //
1743                                         // We then specialize local variable to capture all generic parameters
1744                                         // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1745                                         //
1746                                 }
1747                         }
1748
1749                         Label l_initialized = ec.DefineLabel ();
1750
1751                         if (am_cache != null) {
1752                                 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1753                                 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1754                         }
1755
1756                         //
1757                         // Load method delegate implementation
1758                         //
1759
1760                         if (is_static) {
1761                                 ec.EmitNull ();
1762                         } else if (storey != null) {
1763                                 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1764                                 if (e != null) {
1765                                         e.Emit (ec);
1766                                 }
1767                         } else {
1768                                 ec.EmitThis ();
1769
1770                                 //
1771                                 // Special case for value type storey where this is not lifted but
1772                                 // droped off to parent class
1773                                 //
1774                                 for (var b = Block.Parent; b != null; b = b.Parent) {
1775                                         if (b.ParametersBlock.StateMachine != null) {
1776                                                 ec.Emit (OpCodes.Ldfld, b.ParametersBlock.StateMachine.HoistedThis.Field.Spec);
1777                                                 break;
1778                                         }
1779                                 }
1780                         }
1781
1782                         var delegate_method = method.Spec;
1783                         if (storey != null && storey.MemberName.IsGeneric) {
1784                                 TypeSpec t = storey.Instance.Type;
1785
1786                                 //
1787                                 // Mutate anonymous method instance type if we are in nested
1788                                 // hoisted generic anonymous method storey
1789                                 //
1790                                 if (ec.IsAnonymousStoreyMutateRequired) {
1791                                         t = storey.Mutator.Mutate (t);
1792                                 }
1793
1794                                 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1795                         } else {
1796                                 if (delegate_method.IsGeneric)
1797                                         delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
1798
1799                                 ec.Emit (OpCodes.Ldftn, delegate_method);
1800                         }
1801
1802                         var constructor_method = Delegate.GetConstructor (type);
1803                         ec.Emit (OpCodes.Newobj, constructor_method);
1804
1805                         if (am_cache != null) {
1806                                 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1807                                 ec.MarkLabel (l_initialized);
1808                                 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1809                         }
1810                 }
1811
1812                 public override void EmitStatement (EmitContext ec)
1813                 {
1814                         throw new NotImplementedException ();
1815                 }
1816
1817                 //
1818                 // Look for the best storey for this anonymous method
1819                 //
1820                 AnonymousMethodStorey FindBestMethodStorey ()
1821                 {
1822                         //
1823                         // Use the nearest parent block which has a storey
1824                         //
1825                         for (Block b = Block.Parent; b != null; b = b.Parent) {
1826                                 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1827                                 if (s != null)
1828                                         return s;
1829                         }
1830                                         
1831                         return null;
1832                 }
1833
1834                 public override string GetSignatureForError ()
1835                 {
1836                         return TypeManager.CSharpName (type);
1837                 }
1838         }
1839
1840         //
1841         // Anonymous type container
1842         //
1843         public class AnonymousTypeClass : CompilerGeneratedContainer
1844         {
1845                 public const string ClassNamePrefix = "<>__AnonType";
1846                 public const string SignatureForError = "anonymous type";
1847                 
1848                 readonly IList<AnonymousTypeParameter> parameters;
1849
1850                 private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1851                         : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
1852                 {
1853                         this.parameters = parameters;
1854                 }
1855
1856                 public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1857                 {
1858                         string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
1859
1860                         ParametersCompiled all_parameters;
1861                         TypeParameters tparams = null;
1862                         SimpleName[] t_args;
1863
1864                         if (parameters.Count == 0) {
1865                                 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1866                                 t_args = null;
1867                         } else {
1868                                 t_args = new SimpleName[parameters.Count];
1869                                 tparams = new TypeParameters ();
1870                                 Parameter[] ctor_params = new Parameter[parameters.Count];
1871                                 for (int i = 0; i < parameters.Count; ++i) {
1872                                         AnonymousTypeParameter p = parameters[i];
1873                                         for (int ii = 0; ii < i; ++ii) {
1874                                                 if (parameters[ii].Name == p.Name) {
1875                                                         parent.Compiler.Report.Error (833, parameters[ii].Location,
1876                                                                 "`{0}': An anonymous type cannot have multiple properties with the same name",
1877                                                                         p.Name);
1878
1879                                                         p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
1880                                                         parameters[i] = p;
1881                                                         break;
1882                                                 }
1883                                         }
1884
1885                                         t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1886                                         tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
1887                                         ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
1888                                 }
1889
1890                                 all_parameters = new ParametersCompiled (ctor_params);
1891                         }
1892
1893                         //
1894                         // Create generic anonymous type host with generic arguments
1895                         // named upon properties names
1896                         //
1897                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
1898
1899                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1900                                 null, all_parameters, loc);
1901                         c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
1902
1903                         // 
1904                         // Create fields and constructor body with field initialization
1905                         //
1906                         bool error = false;
1907                         for (int i = 0; i < parameters.Count; ++i) {
1908                                 AnonymousTypeParameter p = parameters [i];
1909
1910                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
1911                                         new MemberName ("<" + p.Name + ">", p.Location), null);
1912
1913                                 if (!a_type.AddField (f)) {
1914                                         error = true;
1915                                         continue;
1916                                 }
1917
1918                                 c.Block.AddStatement (new StatementExpression (
1919                                         new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1920                                                 c.Block.GetParameterReference (i, p.Location))));
1921
1922                                 ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
1923                                 get_block.AddStatement (new Return (
1924                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
1925
1926                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1927                                         new MemberName (p.Name, p.Location), null);
1928                                 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1929                                 prop.Get.Block = get_block;
1930                                 a_type.AddMember (prop);
1931                         }
1932
1933                         if (error)
1934                                 return null;
1935
1936                         a_type.AddConstructor (c);
1937                         return a_type;
1938                 }
1939                 
1940                 protected override bool DoDefineMembers ()
1941                 {
1942                         if (!base.DoDefineMembers ())
1943                                 return false;
1944
1945                         Location loc = Location;
1946
1947                         var equals_parameters = ParametersCompiled.CreateFullyResolved (
1948                                 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
1949
1950                         Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
1951                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1952                                 equals_parameters, null);
1953
1954                         equals_parameters[0].Resolve (equals, 0);
1955
1956                         Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
1957                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1958                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1959
1960                         ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1961
1962                         TypeExpr current_type;
1963                         if (CurrentTypeParameters != null) {
1964                                 var targs = new TypeArguments ();
1965                                 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1966                                         targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
1967                                 }
1968
1969                                 current_type = new GenericTypeExpr (Definition, targs, loc);
1970                         } else {
1971                                 current_type = new TypeExpression (Definition, loc);
1972                         }
1973
1974                         var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
1975                         equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
1976                         var other_variable = new LocalVariableReference (li_other, loc);
1977
1978                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1979                                 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1980
1981                         Expression rs_equals = null;
1982                         Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
1983                         Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
1984                         for (int i = 0; i < parameters.Count; ++i) {
1985                                 var p = parameters [i];
1986                                 var f = (Field) Members [i * 2];
1987
1988                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1989                                         system_collections_generic, "EqualityComparer",
1990                                                 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
1991                                                 "Default", loc);
1992
1993                                 Arguments arguments_equal = new Arguments (2);
1994                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1995                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1996
1997                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1998                                         "Equals", loc), arguments_equal);
1999
2000                                 Arguments arguments_hashcode = new Arguments (1);
2001                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2002                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2003                                         "GetHashCode", loc), arguments_hashcode);
2004
2005                                 IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);                         
2006                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
2007                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
2008                                         FNV_prime, loc);
2009
2010                                 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
2011                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
2012                                         new Invocation (new MemberAccess (
2013                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2014                                         new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
2015
2016                                 if (rs_equals == null) {
2017                                         rs_equals = field_equal;
2018                                         string_concat = new Binary (Binary.Operator.Addition,
2019                                                 string_concat,
2020                                                 new Binary (Binary.Operator.Addition,
2021                                                         new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
2022                                                         field_to_string,
2023                                                         loc),
2024                                                 loc);
2025                                         continue;
2026                                 }
2027
2028                                 //
2029                                 // Implementation of ToString () body using string concatenation
2030                                 //                              
2031                                 string_concat = new Binary (Binary.Operator.Addition,
2032                                         new Binary (Binary.Operator.Addition,
2033                                                 string_concat,
2034                                                 new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc),
2035                                                 loc),
2036                                         field_to_string,
2037                                         loc);
2038
2039                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
2040                         }
2041
2042                         string_concat = new Binary (Binary.Operator.Addition,
2043                                 string_concat,
2044                                 new StringConstant (Compiler.BuiltinTypes, " }", loc),
2045                                 loc);
2046
2047                         //
2048                         // Equals (object obj) override
2049                         //              
2050                         var other_variable_assign = new TemporaryVariableReference (li_other, loc);
2051                         equals_block.AddStatement (new StatementExpression (
2052                                 new SimpleAssign (other_variable_assign,
2053                                         new As (equals_block.GetParameterReference (0, loc),
2054                                                 current_type, loc), loc)));
2055
2056                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
2057                         if (rs_equals != null)
2058                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
2059                         equals_block.AddStatement (new Return (equals_test, loc));
2060
2061                         equals.Block = equals_block;
2062                         equals.Define ();
2063                         Members.Add (equals);
2064
2065                         //
2066                         // GetHashCode () override
2067                         //
2068                         Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
2069                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
2070                                 new MemberName ("GetHashCode", loc),
2071                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
2072
2073                         //
2074                         // Modified FNV with good avalanche behavior and uniform
2075                         // distribution with larger hash sizes.
2076                         //
2077                         // const int FNV_prime = 16777619;
2078                         // int hash = (int) 2166136261;
2079                         // foreach (int d in data)
2080                         //     hash = (hash ^ d) * FNV_prime;
2081                         // hash += hash << 13;
2082                         // hash ^= hash >> 7;
2083                         // hash += hash << 3;
2084                         // hash ^= hash >> 17;
2085                         // hash += hash << 5;
2086
2087                         ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
2088                         Block hashcode_block = new Block (hashcode_top, loc, loc);
2089                         hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
2090
2091                         var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
2092                         hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
2093                         LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
2094                         hashcode_block.AddStatement (new StatementExpression (
2095                                 new SimpleAssign (hash_variable_assign, rs_hashcode)));
2096
2097                         var hash_variable = new LocalVariableReference (li_hash, loc);
2098                         hashcode_block.AddStatement (new StatementExpression (
2099                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2100                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc), loc), loc)));
2101                         hashcode_block.AddStatement (new StatementExpression (
2102                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2103                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc), loc), loc)));
2104                         hashcode_block.AddStatement (new StatementExpression (
2105                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2106                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc), loc), loc)));
2107                         hashcode_block.AddStatement (new StatementExpression (
2108                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2109                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc), loc), loc)));
2110                         hashcode_block.AddStatement (new StatementExpression (
2111                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2112                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc), loc), loc)));
2113
2114                         hashcode_block.AddStatement (new Return (hash_variable, loc));
2115                         hashcode.Block = hashcode_top;
2116                         hashcode.Define ();
2117                         Members.Add (hashcode);
2118
2119                         //
2120                         // ToString () override
2121                         //
2122
2123                         ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
2124                         tostring_block.AddStatement (new Return (string_concat, loc));
2125                         tostring.Block = tostring_block;
2126                         tostring.Define ();
2127                         Members.Add (tostring);
2128
2129                         return true;
2130                 }
2131
2132                 public override string GetSignatureForError ()
2133                 {
2134                         return SignatureForError;
2135                 }
2136
2137                 public override CompilationSourceFile GetCompilationSourceFile ()
2138                 {
2139                         return null;
2140                 }
2141
2142                 public IList<AnonymousTypeParameter> Parameters {
2143                         get {
2144                                 return parameters;
2145                         }
2146                 }
2147         }
2148 }