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