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