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