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