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