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