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