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