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