2009-08-03 Marek Safar <marek.safar@gmail.com>
[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, DeclSpace 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.ContainerType, 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 (EmitContext 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 (EmitContext 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.GenericDeclContainer.TypeParameters;
298
299                                 TypeArguments targs = new TypeArguments ();
300
301                                 if (tparams.Length < CountTypeParameters) {
302                                         TypeParameter[] parent_tparams = ec.DeclContainer.Parent.PartialContainer.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                         Expression e = new New (storey_type_expr, null, Location).Resolve (ec);
316                         e.Emit (ec);
317
318                         Instance = new LocalTemporary (storey_type_expr.Type);
319                         Instance.Store (ec);
320
321                         EmitHoistedFieldsInitialization (ec);
322
323                         SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
324                         SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
325                 }
326
327                 void EmitHoistedFieldsInitialization (EmitContext ec)
328                 {
329                         //
330                         // Initialize all storey reference fields by using local or hoisted variables
331                         //
332                         if (used_parent_storeys != null) {
333                                 foreach (StoreyFieldPair sf in used_parent_storeys) {
334                                         //
335                                         // Setting local field
336                                         //
337                                         Expression instace_expr = GetStoreyInstanceExpression (ec);
338                                         FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
339                                                 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
340                                                 new FieldExpr (sf.Field.FieldBuilder, Location);
341                                         f_set_expr.InstanceExpression = instace_expr;
342
343                                         SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
344                                         if (a.Resolve (ec) != null)
345                                                 a.EmitStatement (ec);
346                                 }
347                         }
348
349                         //
350                         // Define hoisted `this' in top-level storey only 
351                         //
352                         if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
353                                 AddCapturedThisField (ec);
354                                 OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
355                         }
356
357                         //
358                         // Setting currect anonymous method to null blocks any further variable hoisting
359                         //
360                         AnonymousExpression ae = ec.CurrentAnonymousMethod;
361                         ec.CurrentAnonymousMethod = null;
362
363                         if (hoisted_params != null) {
364                                 EmitHoistedParameters (ec, hoisted_params);
365                         }
366
367                         ec.CurrentAnonymousMethod = ae;
368                 }
369
370                 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
371                 {
372                         foreach (HoistedParameter hp in hoisted) {
373                                 hp.EmitHoistingAssignment (ec);
374                         }
375                 }
376
377                 public override void EmitType ()
378                 {
379                         SymbolWriter.DefineAnonymousScope (ID);
380
381                         if (hoisted_this != null)
382                                 hoisted_this.EmitSymbolInfo ();
383
384                         if (hoisted_locals != null) {
385                                 foreach (HoistedVariable local in hoisted_locals)
386                                         local.EmitSymbolInfo ();
387                         }
388
389                         if (hoisted_params != null) {
390                                 foreach (HoistedParameter param in hoisted_params)
391                                         param.EmitSymbolInfo ();
392                         }
393
394                         if (used_parent_storeys != null) {
395                                 foreach (StoreyFieldPair sf in used_parent_storeys) {
396                                         SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
397                                 }
398                         }
399
400                         base.EmitType ();
401                 }
402
403                 public AnonymousMethodStorey GetGenericStorey ()
404                 {
405                         DeclSpace storey = this;
406                         while (storey != null && storey.CurrentTypeParameters.Length == 0)
407                                 storey = storey.Parent;
408
409                         return storey as AnonymousMethodStorey;
410                 }
411
412                 //
413                 // Returns a field which holds referenced storey instance
414                 //
415                 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
416                 {
417                         if (used_parent_storeys == null)
418                                 return null;
419
420                         foreach (StoreyFieldPair sf in used_parent_storeys) {
421                                 if (sf.Storey == storey)
422                                         return sf.Field;
423                         }
424
425                         return null;
426                 }
427
428                 //
429                 // Creates storey instance expression regardless of currect IP
430                 //
431                 public Expression GetStoreyInstanceExpression (EmitContext ec)
432                 {
433                         AnonymousExpression am = ec.CurrentAnonymousMethod;
434
435                         //
436                         // Access from original block -> storey
437                         //
438                         if (am == null)
439                                 return Instance;
440
441                         //
442                         // Access from anonymous method implemented as a static -> storey
443                         //
444                         if (am.Storey == null)
445                                 return Instance;
446
447                         Field f = am.Storey.GetReferencedStoreyField (this);
448                         if (f == null) {
449                                 if (am.Storey == this) {
450                                         //
451                                         // Access inside of same storey (S -> S)
452                                         //
453                                         return new CompilerGeneratedThis (TypeBuilder, Location);
454                                 }
455                                 //
456                                 // External field access
457                                 //
458                                 return Instance;
459                         }
460
461                         //
462                         // Storey was cached to local field
463                         //
464                         FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
465                         f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
466                         return f_ind;
467                 }
468
469                 protected virtual string GetVariableMangledName (LocalInfo local_info)
470                 {
471                         //
472                         // No need to mangle anonymous method hoisted variables cause they
473                         // are hoisted in their own scopes
474                         //
475                         return local_info.Name;
476                 }
477
478                 public HoistedThis HoistedThis {
479                         get { return hoisted_this; }
480                 }
481
482                 //
483                 // Mutate type dispatcher
484                 //
485                 public Type MutateType (Type type)
486                 {
487 #if GMCS_SOURCE
488                         if (TypeManager.IsGenericType (type))
489                                 return MutateGenericType (type);
490
491                         if (TypeManager.IsGenericParameter (type))
492                                 return MutateGenericArgument (type);
493
494                         if (type.IsArray)
495                                 return MutateArrayType (type);
496 #endif
497                         return type;
498                 }
499
500                 //
501                 // Changes method type arguments (MVAR) to storey (VAR) type arguments
502                 //
503                 public MethodInfo MutateGenericMethod (MethodInfo method)
504                 {
505 #if GMCS_SOURCE
506                         Type [] t_args = TypeManager.GetGenericArguments (method);
507                         if (TypeManager.IsGenericType (method.DeclaringType)) {
508                                 Type t = MutateGenericType (method.DeclaringType);
509                                 if (t != method.DeclaringType) {
510                                         method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
511                                         if (method.Module == Module.Builder)
512                                                 method = TypeBuilder.GetMethod (t, method);
513                                         else
514                                                 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
515                                 }                               
516                         }
517
518                         if (t_args == null || t_args.Length == 0)
519                                 return method;
520
521                         for (int i = 0; i < t_args.Length; ++i)
522                                 t_args [i] = MutateType (t_args [i]);
523
524                         return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
525 #else
526                         throw new NotSupportedException ();
527 #endif
528                 }
529
530                 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
531                 {
532 #if GMCS_SOURCE         
533                         if (TypeManager.IsGenericType (ctor.DeclaringType)) {
534                                 Type t = MutateGenericType (ctor.DeclaringType);
535                                 if (t != ctor.DeclaringType) {
536                                         ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
537                                         if (ctor.Module == Module.Builder)
538                                                 return TypeBuilder.GetConstructor (t, ctor);
539                                                 
540                                         return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
541                                 }
542                         }
543 #endif
544                         return ctor;
545                 }
546                 
547                 public FieldInfo MutateField (FieldInfo field)
548                 {
549 #if GMCS_SOURCE
550                         if (TypeManager.IsGenericType (field.DeclaringType)) {
551                                 Type t = MutateGenericType (field.DeclaringType);
552                                 if (t != field.DeclaringType) {
553                                         field = TypeManager.DropGenericTypeArguments (field.DeclaringType).GetField (field.Name, TypeManager.AllMembers);
554                                         if (field.Module == Module.Builder)
555                                                 return TypeBuilder.GetField (t, field);
556
557                                         return FieldInfo.GetFieldFromHandle (field.FieldHandle, t.TypeHandle);                                          
558                                 }
559                         }
560 #endif
561                         return field;
562                 }               
563
564 #if GMCS_SOURCE
565                 protected Type MutateArrayType (Type array)
566                 {
567                         Type element = TypeManager.GetElementType (array);
568                         if (element.IsArray) {
569                                 element = MutateArrayType (element);
570                         } else if (TypeManager.IsGenericParameter (element)) {
571                                 element = MutateGenericArgument (element);
572                         } else if (TypeManager.IsGenericType (element)) {
573                                 element = MutateGenericType (element);
574                         } else {
575                                 return array;
576                         }
577
578                         int rank = array.GetArrayRank ();
579                         if (rank == 1)
580                                 return element.MakeArrayType ();
581
582                         return element.MakeArrayType (rank);
583                 }
584
585                 protected Type MutateGenericType (Type type)
586                 {
587                         Type [] t_args = TypeManager.GetTypeArguments (type);
588                         if (t_args == null || t_args.Length == 0)
589                                 return type;
590
591                         for (int i = 0; i < t_args.Length; ++i)
592                                 t_args [i] = MutateType (t_args [i]);
593
594                         return TypeManager.DropGenericTypeArguments (type).MakeGenericType (t_args);
595                 }
596 #endif
597
598                 //
599                 // Changes method generic argument (MVAR) to type generic argument (VAR)
600                 //
601                 public Type MutateGenericArgument (Type type)
602                 {
603                         foreach (TypeParameter tp in CurrentTypeParameters) {
604                                 if (tp.Name == type.Name) {
605                                         return tp.Type;
606                                 }
607                         }
608
609                         return type;
610                 }
611
612                 public ArrayList ReferencesFromChildrenBlock {
613                         get { return children_references; }
614                 }
615
616                 public static void Reset ()
617                 {
618                         unique_id = 0;
619                 }               
620         }
621
622         public abstract class HoistedVariable
623         {
624                 class ExpressionTreeProxy : Expression
625                 {
626                         readonly HoistedVariable hv;
627
628                         public ExpressionTreeProxy (HoistedVariable hv)
629                         {
630                                 this.hv = hv;
631                         }
632
633                         public override Expression CreateExpressionTree (EmitContext ec)
634                         {
635                                 throw new NotSupportedException ("ET");
636                         }
637
638                         public override Expression DoResolve (EmitContext ec)
639                         {
640                                 eclass = ExprClass.Value;
641                                 type = TypeManager.expression_type_expr.Type;
642                                 return this;
643                         }
644
645                         public override void Emit (EmitContext ec)
646                         {
647                                 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
648                                 // This should never fail
649                                 e = e.Resolve (ec);
650                                 if (e != null)
651                                         e.Emit (ec);
652                         }
653                 }
654         
655                 protected readonly AnonymousMethodStorey storey;
656                 protected Field field;
657                 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
658                 FieldExpr cached_outer_access;
659
660                 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
661                         : this (storey, storey.AddCapturedVariable (name, type))
662                 {
663                 }
664
665                 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
666                 {
667                         this.storey = storey;
668                         this.field = field;
669                 }
670
671                 public void AddressOf (EmitContext ec, AddressOp mode)
672                 {
673                         GetFieldExpression (ec).AddressOf (ec, mode);
674                 }
675
676                 public Expression CreateExpressionTree (EmitContext ec)
677                 {
678                         return new ExpressionTreeProxy (this);
679                 }
680
681                 public void Emit (EmitContext ec)
682                 {
683                         GetFieldExpression (ec).Emit (ec);
684                 }
685
686                 //
687                 // Creates field access expression for hoisted variable
688                 //
689                 protected FieldExpr GetFieldExpression (EmitContext ec)
690                 {
691                         if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
692                                 if (cached_outer_access != null)
693                                         return cached_outer_access;
694
695                                 //
696                                 // When setting top-level hoisted variable in generic storey
697                                 // change storey generic types to method generic types (VAR -> MVAR)
698                                 //
699                                 cached_outer_access = storey.MemberName.IsGeneric ?
700                                         new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
701                                         new FieldExpr (field.FieldBuilder, field.Location);
702
703                                 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
704                                 cached_outer_access.Resolve (ec);
705                                 return cached_outer_access;
706                         }
707
708                         FieldExpr inner_access;
709                         if (cached_inner_access != null) {
710                                 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
711                         } else {
712                                 inner_access = null;
713                                 cached_inner_access = new Hashtable (4);
714                         }
715
716                         if (inner_access == null) {
717                                 inner_access = field.Parent.MemberName.IsGeneric ?
718                                         new FieldExpr (field.FieldBuilder, field.Parent.CurrentType, field.Location) :
719                                         new FieldExpr (field.FieldBuilder, field.Location);
720                                                         
721                                 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
722                                 inner_access.Resolve (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 (EmitContext 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 (ec) != 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), ec.GetThis (field.Location));
826                         if (a.Resolve (ec) != 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 (EmitContext ec, Type delegate_type)
875                 {
876                         using (ec.With (EmitContext.Flags.InferReturnType, false)) {
877                                 using (ec.Set (EmitContext.Flags.ProbingMode)) {
878                                         return Compatible (ec, delegate_type) != null;
879                                 }
880                         }
881                 }
882
883                 protected Type CompatibleChecks (EmitContext 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 (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1008                 {
1009                         AnonymousMethodBody am;
1010                         using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1011                                 am = CompatibleMethod (ec, tic, TypeManager.null_type, delegate_type);
1012                         }
1013                         
1014                         if (am == null)
1015                                 return null;
1016
1017                         // Stop referencing gmcs NullLiteral type
1018                         if (am.ReturnType == TypeManager.null_type)
1019                                 am.ReturnType = null;
1020
1021                         return am.ReturnType;
1022                 }
1023
1024                 //
1025                 // Returns AnonymousMethod container if this anonymous method
1026                 // expression can be implicitly converted to the delegate type `delegate_type'
1027                 //
1028                 public Expression Compatible (EmitContext ec, Type type)
1029                 {
1030                         Expression am = (Expression) compatibles [type];
1031                         if (am != null)
1032                                 return am;
1033
1034                         Type delegate_type = CompatibleChecks (ec, type);
1035                         if (delegate_type == null)
1036                                 return null;
1037
1038                         //
1039                         // At this point its the first time we know the return type that is 
1040                         // needed for the anonymous method.  We create the method here.
1041                         //
1042
1043                         MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1044                                 ec.ContainerType, delegate_type);
1045                         Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1046
1047 #if MS_COMPATIBLE
1048                         Type[] g_args = delegate_type.GetGenericArguments ();
1049                         if (return_type.IsGenericParameter)
1050                                 return_type = g_args [return_type.GenericParameterPosition];
1051 #endif
1052
1053                         //
1054                         // Second: the return type of the delegate must be compatible with 
1055                         // the anonymous type.   Instead of doing a pass to examine the block
1056                         // we satisfy the rule by setting the return type on the EmitContext
1057                         // to be the delegate type return type.
1058                         //
1059
1060                         try {
1061                                 int errors = Report.Errors;
1062                                 am = CompatibleMethod (ec, null, return_type, delegate_type);
1063                                 if (am != null && delegate_type != type && errors == Report.Errors)
1064                                         am = CreateExpressionTree (ec, delegate_type);
1065
1066                                 if (!ec.IsInProbingMode)
1067                                         compatibles.Add (type, am == null ? EmptyExpression.Null : am);
1068
1069                                 return am;
1070                         } catch (CompletionResult){
1071                                 throw;
1072                         } catch (Exception e) {
1073                                 throw new InternalErrorException (e, loc);
1074                         }
1075                 }
1076
1077                 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1078                 {
1079                         return CreateExpressionTree (ec);
1080                 }
1081
1082                 public override Expression CreateExpressionTree (EmitContext ec)
1083                 {
1084                         Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1085                         return null;
1086                 }
1087
1088                 protected virtual ParametersCompiled ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1089                 {
1090                         AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1091
1092                         if (Parameters == ParametersCompiled.Undefined) {
1093                                 //
1094                                 // We provide a set of inaccessible parameters
1095                                 //
1096                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1097
1098                                 for (int i = 0; i < delegate_parameters.Count; i++) {
1099                                         Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1100                                         if (i_mod == Parameter.Modifier.OUT) {
1101                                                 Report.Error (1688, loc, "Cannot convert anonymous " +
1102                                                                   "method block without a parameter list " +
1103                                                                   "to delegate type `{0}' because it has " +
1104                                                                   "one or more `out' parameters.",
1105                                                                   TypeManager.CSharpName (delegate_type));
1106                                                 return null;
1107                                         }
1108                                         fixedpars[i] = new Parameter (
1109                                                 null, null,
1110                                                 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1111                                 }
1112
1113                                 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1114                         }
1115
1116                         if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1117                                 return null;
1118                         }
1119
1120                         return Parameters;
1121                 }
1122
1123                 public override Expression DoResolve (EmitContext ec)
1124                 {
1125                         if (!ec.IsAnonymousMethodAllowed) {
1126                                 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1127                                 return null;
1128                         }
1129
1130                         //
1131                         // Set class type, set type
1132                         //
1133
1134                         eclass = ExprClass.Value;
1135
1136                         //
1137                         // This hack means `The type is not accessible
1138                         // anywhere', we depend on special conversion
1139                         // rules.
1140                         // 
1141                         type = InternalType.AnonymousMethod;
1142
1143                         if ((Parameters != null) && !Parameters.Resolve (ec))
1144                                 return null;
1145
1146                         // FIXME: The emitted code isn't very careful about reachability
1147                         // so, ensure we have a 'ret' at the end
1148                         if (ec.CurrentBranching != null &&
1149                             ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1150                                 ec.NeedReturnLabel ();
1151
1152                         return this;
1153                 }
1154
1155                 public override void Emit (EmitContext ec)
1156                 {
1157                         // nothing, as we only exist to not do anything.
1158                 }
1159
1160                 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1161                 {
1162                         Report.Error (1686, loc,
1163                                 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1164                                 var.Name);
1165                 }
1166
1167                 public override string GetSignatureForError ()
1168                 {
1169                         return ExprClassName;
1170                 }
1171
1172                 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1173                 {
1174                         ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1175                         if (p == null)
1176                                 return null;
1177
1178                         ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1179
1180                         AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1181                         if (!anonymous.Compatible (ec))
1182                                 return null;
1183
1184                         return anonymous;
1185                 }
1186
1187                 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
1188                 {
1189                         return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1190                 }
1191
1192                 protected override void CloneTo (CloneContext clonectx, Expression t)
1193                 {
1194                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1195
1196                         target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1197                 }
1198         }
1199
1200         //
1201         // Abstract expression for any block which requires variables hoisting
1202         //
1203         public abstract class AnonymousExpression : Expression
1204         {
1205                 protected class AnonymousMethodMethod : Method
1206                 {
1207                         public readonly AnonymousExpression AnonymousMethod;
1208                         public readonly AnonymousMethodStorey Storey;
1209                         readonly string RealName;
1210
1211                         public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1212                                                           GenericMethod generic, TypeExpr return_type,
1213                                                           int mod, string real_name, MemberName name,
1214                                                           ParametersCompiled parameters)
1215                                 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1216                                                 name, parameters, null)
1217                         {
1218                                 this.AnonymousMethod = am;
1219                                 this.Storey = storey;
1220                                 this.RealName = real_name;
1221
1222                                 Parent.PartialContainer.AddMethod (this);
1223                                 Block = am.Block;
1224                         }
1225
1226                         public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1227                         {
1228                                 EmitContext aec = AnonymousMethod.aec;
1229                                 aec.ig = ig;
1230                                 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1231                                 return aec;
1232                         }
1233
1234                         protected override bool ResolveMemberType ()
1235                         {
1236                                 if (!base.ResolveMemberType ())
1237                                         return false;
1238
1239                                 if (Storey != null && Storey.IsGeneric) {
1240                                         AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1241                                         if (gstorey != null) {
1242                                                 if (!Parameters.IsEmpty) {
1243                                                         Type [] ptypes = Parameters.Types;
1244                                                         for (int i = 0; i < ptypes.Length; ++i)
1245                                                                 ptypes [i] = gstorey.MutateType (ptypes [i]);
1246                                                 }
1247
1248                                                 member_type = gstorey.MutateType (member_type);
1249                                         }
1250                                 }
1251
1252                                 return true;
1253                         }
1254
1255                         public override void Emit ()
1256                         {
1257                                 //
1258                                 // Before emitting any code we have to change all MVAR references to VAR
1259                                 // when the method is of generic type and has hoisted variables
1260                                 //
1261                                 if (Storey == Parent && Storey.IsGeneric) {
1262                                         AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1263                                         if (gstorey != null) {
1264                                                 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1265                                                 block.MutateHoistedGenericType (gstorey);
1266                                         }
1267                                 }
1268
1269                                 if (MethodBuilder == null) {
1270                                         Define ();
1271                                 }
1272
1273                                 base.Emit ();
1274                         }
1275
1276                         public override void EmitExtraSymbolInfo (SourceMethod source)
1277                         {
1278                                 source.SetRealMethodName (RealName);
1279                         }
1280                 }
1281
1282                 //
1283                 // The block that makes up the body for the anonymous method
1284                 //
1285                 protected readonly ToplevelBlock Block;
1286
1287                 public Type ReturnType;
1288                 protected EmitContext aec;
1289
1290                 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1291                 {
1292                         this.ReturnType = return_type;
1293                         this.Block = block;
1294                         this.loc = loc;
1295                 }
1296
1297                 public abstract string ContainerType { get; }
1298                 public abstract bool IsIterator { get; }
1299                 public abstract AnonymousMethodStorey Storey { get; }
1300
1301                 public bool Compatible (EmitContext ec)
1302                 {
1303                         // TODO: Implement clone
1304                         aec = new EmitContext (
1305                                 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1306                                 Location, null, ReturnType,
1307                                 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1308
1309                         aec.CurrentAnonymousMethod = this;
1310                         aec.IsStatic = ec.IsStatic;
1311
1312                         IDisposable aec_dispose = null;
1313                         EmitContext.Flags flags = 0;
1314                         if (ec.InferReturnType)
1315                                 flags |= EmitContext.Flags.InferReturnType;
1316
1317                         if (ec.IsInProbingMode)
1318                                 flags |= EmitContext.Flags.ProbingMode;
1319
1320                         if (ec.IsInFieldInitializer)
1321                                 flags |= EmitContext.Flags.InFieldInitializer;
1322
1323                         if (ec.IsInUnsafeScope)
1324                                 flags |= EmitContext.Flags.InUnsafe;
1325
1326                         // HACK: Flag with 0 cannot be set 
1327                         if (flags != 0)
1328                                 aec_dispose = aec.Set (flags);
1329
1330                         bool unreachable;
1331                         bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1332
1333                         if (ec.InferReturnType)
1334                                 ReturnType = aec.ReturnType;
1335
1336                         if (aec_dispose != null) {
1337                                 aec_dispose.Dispose ();
1338                         }
1339
1340                         return res;
1341                 }
1342
1343                 public void SetHasThisAccess ()
1344                 {
1345                         Block.HasCapturedThis = true;
1346                         ExplicitBlock b = Block.Parent.Explicit;
1347
1348                         while (b != null) {
1349                                 if (b.HasCapturedThis)
1350                                         return;
1351
1352                                 b.HasCapturedThis = true;
1353                                 b = b.Parent == null ? null : b.Parent.Explicit;
1354                         }
1355                 }
1356         }
1357
1358         public class AnonymousMethodBody : AnonymousExpression
1359         {
1360                 protected readonly ParametersCompiled parameters;
1361                 AnonymousMethodStorey storey;
1362
1363                 AnonymousMethodMethod method;
1364                 Field am_cache;
1365
1366                 static int unique_id;
1367
1368                 public AnonymousMethodBody (ParametersCompiled parameters,
1369                                         ToplevelBlock block, Type return_type, Type delegate_type,
1370                                         Location loc)
1371                         : base (block, return_type, loc)
1372                 {
1373                         this.type = delegate_type;
1374                         this.parameters = parameters;
1375                 }
1376
1377                 public override string ContainerType {
1378                         get { return "anonymous method"; }
1379                 }
1380
1381                 public override AnonymousMethodStorey Storey {
1382                         get { return storey; }
1383                 }
1384
1385                 public override bool IsIterator {
1386                         get { return false; }
1387                 }
1388
1389                 public override Expression CreateExpressionTree (EmitContext ec)
1390                 {
1391                         Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1392                         return null;
1393                 }
1394
1395                 bool Define (EmitContext ec)
1396                 {
1397                         if (aec == null && !Compatible (ec))
1398                                 return false;
1399
1400                         return true;
1401                 }
1402
1403                 //
1404                 // Creates a host for the anonymous method
1405                 //
1406                 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1407                 {
1408                         //
1409                         // Anonymous method body can be converted to
1410                         //
1411                         // 1, an instance method in current scope when only `this' is hoisted
1412                         // 2, a static method in current scope when neither `this' nor any variable is hoisted
1413                         // 3, an instance method in compiler generated storey when any hoisted variable exists
1414                         //
1415
1416                         int modifiers;
1417                         if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1418                                 storey = FindBestMethodStorey ();
1419                                 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1420                         } else {
1421                                 if (ec.CurrentAnonymousMethod != null)
1422                                         storey = ec.CurrentAnonymousMethod.Storey;
1423
1424                                 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1425                         }
1426
1427                         DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1428
1429                         MemberCore mc = ec.ResolveContext as MemberCore;
1430                         string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1431                                 "m", null, unique_id++);
1432
1433                         MemberName member_name;
1434                         GenericMethod generic_method;
1435                         if (storey == null && mc.MemberName.IsGeneric) {
1436                                 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1437
1438                                 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1439                                         new TypeExpression (ReturnType, Location), parameters);
1440
1441                                 ArrayList list = new ArrayList ();
1442                                 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1443                                         if (tparam.Constraints != null)
1444                                                 list.Add (tparam.Constraints.Clone ());
1445                                 }
1446                                 generic_method.SetParameterInfo (list);
1447                         } else {
1448                                 member_name = new MemberName (name, Location);
1449                                 generic_method = null;
1450                         }
1451
1452                         string real_name = String.Format (
1453                                 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1454                                 parameters.GetSignatureForError ());
1455
1456                         return new AnonymousMethodMethod (parent,
1457                                 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1458                                 real_name, member_name, parameters);
1459                 }
1460
1461                 public override Expression DoResolve (EmitContext ec)
1462                 {
1463                         if (eclass == ExprClass.Invalid) {
1464                                 if (!Define (ec))
1465                                         return null;
1466                         }
1467
1468                         eclass = ExprClass.Value;
1469                         return this;
1470                 }
1471
1472                 public override void Emit (EmitContext ec)
1473                 {
1474                         //
1475                         // Use same anonymous method implementation for scenarios where same
1476                         // code is used from multiple blocks, e.g. field initializers
1477                         //
1478                         if (method == null) {
1479                                 //
1480                                 // Delay an anonymous method definition to avoid emitting unused code
1481                                 // for unreachable blocks or expression trees
1482                                 //
1483                                 method = DoCreateMethodHost (ec);
1484                                 method.Define ();
1485                         }
1486
1487                         bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1488                         if (is_static && am_cache == null) {
1489                                 //
1490                                 // Creates a field cache to store delegate instance if it's not generic
1491                                 //
1492                                 if (!method.MemberName.IsGeneric) {
1493                                         TypeContainer parent = method.Parent.PartialContainer;
1494                                         int id = parent.Fields == null ? 0 : parent.Fields.Count;
1495                                         am_cache = new Field (parent, new TypeExpression (type, loc),
1496                                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1497                                                 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1498                                         am_cache.Define ();
1499                                         parent.AddField (am_cache);
1500                                 } else {
1501                                         // TODO: Implement caching of generated generic static methods
1502                                         //
1503                                         // Idea:
1504                                         //
1505                                         // Some extra class is needed to capture variable generic type
1506                                         // arguments. Maybe we could re-use anonymous types, with a unique
1507                                         // anonymous method id, but they are quite heavy.
1508                                         //
1509                                         // Consider : "() => typeof(T);"
1510                                         //
1511                                         // We need something like
1512                                         // static class Wrap<Tn, Tm, DelegateType> {
1513                                         //              public static DelegateType cache;
1514                                         // }
1515                                         //
1516                                         // We then specialize local variable to capture all generic parameters
1517                                         // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1518                                         //
1519                                 }
1520                         }
1521
1522                         ILGenerator ig = ec.ig;
1523                         Label l_initialized = ig.DefineLabel ();
1524
1525                         if (am_cache != null) {
1526                                 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1527                                 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1528                         }
1529
1530                         //
1531                         // Load method delegate implementation
1532                         //
1533
1534                         if (is_static) {
1535                                 ig.Emit (OpCodes.Ldnull);
1536                         } else if (storey != null) {
1537                                 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1538                                 if (e != null)
1539                                         e.Emit (ec);
1540                         } else {
1541                                 ig.Emit (OpCodes.Ldarg_0);
1542                         }
1543
1544                         MethodInfo delegate_method = method.MethodBuilder;
1545                         if (storey != null && storey.MemberName.IsGeneric) {
1546                                 Type t = storey.Instance.Type;
1547                                 
1548                                 //
1549                                 // Mutate anonymous method instance type if we are in nested
1550                                 // hoisted generic anonymous method storey
1551                                 //
1552                                 if (ec.CurrentAnonymousMethod != null &&
1553                                         ec.CurrentAnonymousMethod.Storey != null &&
1554                                         ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1555                                         t = storey.GetGenericStorey ().MutateType (t);
1556                                 }
1557
1558 #if GMCS_SOURCE
1559                                 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1560 #else
1561                                 throw new NotSupportedException ();
1562 #endif
1563                         }
1564
1565                         ig.Emit (OpCodes.Ldftn, delegate_method);
1566
1567                         ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1568 #if MS_COMPATIBLE
1569             if (type.IsGenericType && type is TypeBuilder)
1570                 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1571 #endif
1572                         ig.Emit (OpCodes.Newobj, constructor_method);
1573
1574                         if (am_cache != null) {
1575                                 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1576                                 ig.MarkLabel (l_initialized);
1577                                 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1578                         }
1579                 }
1580
1581                 //
1582                 // Look for the best storey for this anonymous method
1583                 //
1584                 AnonymousMethodStorey FindBestMethodStorey ()
1585                 {
1586                         //
1587                         // Use the nearest parent block which has a storey
1588                         //
1589                         for (Block b = Block.Parent; b != null; b = b.Parent) {
1590                                 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1591                                 if (s != null)
1592                                         return s;
1593                         }
1594                                         
1595                         return null;
1596                 }
1597
1598                 public override string GetSignatureForError ()
1599                 {
1600                         return TypeManager.CSharpName (type);
1601                 }
1602
1603                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1604                 {
1605                         type = storey.MutateType (type);
1606                 }
1607
1608                 public static void Reset ()
1609                 {
1610                         unique_id = 0;
1611                 }
1612         }
1613
1614         //
1615         // Anonymous type container
1616         //
1617         public class AnonymousTypeClass : CompilerGeneratedClass
1618         {
1619                 sealed class AnonymousParameters : ParametersCompiled
1620                 {
1621                         public AnonymousParameters (params Parameter[] parameters)
1622                                 : base (parameters)
1623                         {
1624                         }
1625
1626                         protected override void ErrorDuplicateName (Parameter p)
1627                         {
1628                                 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1629                                         p.Name);
1630                         }
1631                 }
1632
1633                 static int types_counter;
1634                 public const string ClassNamePrefix = "<>__AnonType";
1635                 public const string SignatureForError = "anonymous type";
1636                 
1637                 readonly ArrayList parameters;
1638
1639                 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1640                         : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1641                 {
1642                         this.parameters = parameters;
1643                 }
1644
1645                 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1646                 {
1647                         if (RootContext.MetadataCompatibilityVersion < MetadataVersion.v2)
1648                                 Report.FeatureIsNotSupported (loc, "anonymous types");
1649
1650                         string name = ClassNamePrefix + types_counter++;
1651
1652                         SimpleName [] t_args = new SimpleName [parameters.Count];
1653                         TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1654                         Parameter [] ctor_params = new Parameter [parameters.Count];
1655                         for (int i = 0; i < parameters.Count; ++i) {
1656                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1657
1658                                 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1659                                 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1660                                 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1661                         }
1662
1663                         //
1664                         // Create generic anonymous type host with generic arguments
1665                         // named upon properties names
1666                         //
1667                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1668                                 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1669
1670                         if (parameters.Count > 0)
1671                                 a_type.SetParameterInfo (null);
1672
1673                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1674                                 null, new AnonymousParameters (ctor_params), null, loc);
1675                         c.Block = new ToplevelBlock (c.Parameters, loc);
1676
1677                         // 
1678                         // Create fields and contructor body with field initialization
1679                         //
1680                         bool error = false;
1681                         for (int i = 0; i < parameters.Count; ++i) {
1682                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1683
1684                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1685                                         new MemberName ("<" + p.Name + ">", p.Location), null);
1686
1687                                 if (!a_type.AddField (f)) {
1688                                         error = true;
1689                                         continue;
1690                                 }
1691
1692                                 c.Block.AddStatement (new StatementExpression (
1693                                         new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1694                                                 c.Block.GetParameterReference (p.Name, p.Location))));
1695
1696                                 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1697                                 get_block.AddStatement (new Return (
1698                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
1699                                 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1700                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1701                                         new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1702                                 a_type.AddProperty (prop);
1703                         }
1704
1705                         if (error)
1706                                 return null;
1707
1708                         a_type.AddConstructor (c);
1709                         return a_type;
1710                 }
1711                 
1712                 public static void Reset ()
1713                 {
1714                         types_counter = 0;
1715                 }
1716
1717                 protected override bool AddToContainer (MemberCore symbol, string name)
1718                 {
1719                         MemberCore mc = (MemberCore) defined_names [name];
1720
1721                         if (mc == null) {
1722                                 defined_names.Add (name, symbol);
1723                                 return true;
1724                         }
1725
1726                         Report.SymbolRelatedToPreviousError (mc);
1727                         return false;
1728                 }
1729
1730                 void DefineOverrides ()
1731                 {
1732                         Location loc = Location;
1733
1734                         Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1735                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1736                                 Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1737
1738                         Method tostring = new Method (this, null, TypeManager.system_string_expr,
1739                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1740                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1741
1742                         ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1743                         TypeExpr current_type;
1744                         if (IsGeneric)
1745                                 current_type = new GenericTypeExpr (this, loc);
1746                         else
1747                                 current_type = new TypeExpression (TypeBuilder, loc);
1748
1749                         equals_block.AddVariable (current_type, "other", loc);
1750                         LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1751
1752                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1753                                 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1754
1755                         Expression rs_equals = null;
1756                         Expression string_concat = new StringConstant ("{", loc);
1757                         Expression rs_hashcode = new IntConstant (-2128831035, loc);
1758                         for (int i = 0; i < parameters.Count; ++i) {
1759                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1760                                 Field f = (Field) Fields [i];
1761
1762                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1763                                         system_collections_generic, "EqualityComparer",
1764                                                 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1765                                                 "Default", loc);
1766
1767                                 Arguments arguments_equal = new Arguments (2);
1768                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1769                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1770
1771                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1772                                         "Equals", loc), arguments_equal);
1773
1774                                 Arguments arguments_hashcode = new Arguments (1);
1775                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1776                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1777                                         "GetHashCode", loc), arguments_hashcode);
1778
1779                                 IntConstant FNV_prime = new IntConstant (16777619, loc);                                
1780                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
1781                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1782                                         FNV_prime);
1783
1784                                 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1785                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1786                                         new Invocation (new MemberAccess (
1787                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1788                                         new StringConstant (string.Empty, loc));
1789
1790                                 if (rs_equals == null) {
1791                                         rs_equals = field_equal;
1792                                         string_concat = new Binary (Binary.Operator.Addition,
1793                                                 string_concat,
1794                                                 new Binary (Binary.Operator.Addition,
1795                                                         new StringConstant (" " + p.Name + " = ", loc),
1796                                                         field_to_string));
1797                                         continue;
1798                                 }
1799
1800                                 //
1801                                 // Implementation of ToString () body using string concatenation
1802                                 //                              
1803                                 string_concat = new Binary (Binary.Operator.Addition,
1804                                         new Binary (Binary.Operator.Addition,
1805                                                 string_concat,
1806                                                 new StringConstant (", " + p.Name + " = ", loc)),
1807                                         field_to_string);
1808
1809                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1810                         }
1811
1812                         string_concat = new Binary (Binary.Operator.Addition,
1813                                 string_concat,
1814                                 new StringConstant (" }", loc));
1815
1816                         //
1817                         // Equals (object obj) override
1818                         //              
1819                         LocalVariableReference other_variable_assign = new LocalVariableReference (equals_block, "other", loc);
1820                         equals_block.AddStatement (new StatementExpression (
1821                                 new SimpleAssign (other_variable_assign,
1822                                         new As (equals_block.GetParameterReference ("obj", loc),
1823                                                 current_type, loc), loc)));
1824
1825                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1826                         if (rs_equals != null)
1827                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1828                         equals_block.AddStatement (new Return (equals_test, loc));
1829
1830                         equals.Block = equals_block;
1831                         equals.Define ();
1832                         AddMethod (equals);
1833
1834                         //
1835                         // GetHashCode () override
1836                         //
1837                         Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1838                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1839                                 new MemberName ("GetHashCode", loc),
1840                                 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1841
1842                         //
1843                         // Modified FNV with good avalanche behavior and uniform
1844                         // distribution with larger hash sizes.
1845                         //
1846                         // const int FNV_prime = 16777619;
1847                         // int hash = (int) 2166136261;
1848                         // foreach (int d in data)
1849                         //     hash = (hash ^ d) * FNV_prime;
1850                         // hash += hash << 13;
1851                         // hash ^= hash >> 7;
1852                         // hash += hash << 3;
1853                         // hash ^= hash >> 17;
1854                         // hash += hash << 5;
1855
1856                         ToplevelBlock hashcode_top = new ToplevelBlock (loc);
1857                         Block hashcode_block = new Block (hashcode_top);
1858                         hashcode_top.AddStatement (new Unchecked (hashcode_block));
1859
1860                         hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1861                         LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1862                         LocalVariableReference hash_variable_assign = new LocalVariableReference (hashcode_block, "hash", loc);
1863                         hashcode_block.AddStatement (new StatementExpression (
1864                                 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1865
1866                         hashcode_block.AddStatement (new StatementExpression (
1867                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1868                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1869                         hashcode_block.AddStatement (new StatementExpression (
1870                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1871                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1872                         hashcode_block.AddStatement (new StatementExpression (
1873                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1874                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1875                         hashcode_block.AddStatement (new StatementExpression (
1876                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1877                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1878                         hashcode_block.AddStatement (new StatementExpression (
1879                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1880                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1881
1882                         hashcode_block.AddStatement (new Return (hash_variable, loc));
1883                         hashcode.Block = hashcode_top;
1884                         hashcode.Define ();
1885                         AddMethod (hashcode);
1886
1887                         //
1888                         // ToString () override
1889                         //
1890
1891                         ToplevelBlock tostring_block = new ToplevelBlock (loc);
1892                         tostring_block.AddStatement (new Return (string_concat, loc));
1893                         tostring.Block = tostring_block;
1894                         tostring.Define ();
1895                         AddMethod (tostring);
1896                 }
1897
1898                 public override bool Define ()
1899                 {
1900                         if (!base.Define ())
1901                                 return false;
1902
1903                         DefineOverrides ();
1904                         return true;
1905                 }
1906
1907                 public override string GetSignatureForError ()
1908                 {
1909                         return SignatureForError;
1910                 }
1911
1912                 public ArrayList Parameters {
1913                         get {
1914                                 return parameters;
1915                         }
1916                 }
1917         }
1918 }