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