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