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