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