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