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