2008-11-13 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
639                 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
640                 {
641                         this.storey = storey;
642
643                         this.field = storey.AddCapturedVariable (name, type);
644                 }
645
646                 public void AddressOf (EmitContext ec, AddressOp mode)
647                 {
648                         GetFieldExpression (ec).AddressOf (ec, mode);
649                 }
650
651                 public Expression CreateExpressionTree (EmitContext ec)
652                 {
653                         return new ExpressionTreeProxy (this);
654                 }
655
656                 public void Emit (EmitContext ec)
657                 {
658                         GetFieldExpression (ec).Emit (ec);
659                 }
660
661                 //
662                 // Creates field access expression for hoisted variable
663                 //
664                 protected FieldExpr GetFieldExpression (EmitContext ec)
665                 {
666                         if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
667                                 //
668                                 // When setting top-level hoisted variable in generic storey
669                                 // change storey generic types to method generic types (VAR -> MVAR)
670                                 //
671                                 FieldExpr outer_access = storey.MemberName.IsGeneric ?
672                                         new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
673                                         new FieldExpr (field.FieldBuilder, field.Location);
674
675                                 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
676                                 outer_access.Resolve (ec);
677                                 return outer_access;
678                         }
679
680                         FieldExpr inner_access;
681                         if (cached_inner_access != null) {
682                                 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
683                         } else {
684                                 inner_access = null;
685                                 cached_inner_access = new Hashtable (4);
686                         }
687
688                         if (inner_access == null) {
689                                 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
690                                 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
691                                 inner_access.Resolve (ec);
692                                 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
693                         }
694
695                         return inner_access;
696                 }
697
698                 public abstract void EmitSymbolInfo ();
699
700                 public void Emit (EmitContext ec, bool leave_copy)
701                 {
702                         GetFieldExpression (ec).Emit (ec, leave_copy);
703                 }
704
705                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
706                 {
707                         GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
708                 }
709         }
710
711         class HoistedParameter : HoistedVariable
712         {
713                 sealed class HoistedFieldAssign : Assign
714                 {
715                         public HoistedFieldAssign (Expression target, Expression source)
716                                 : base (target, source, source.Location)
717                         {
718                         }
719
720                         protected override Expression ResolveConversions (EmitContext ec)
721                         {
722                                 //
723                                 // Implicit conversion check fails for hoisted type arguments
724                                 // as they are of different types (!!0 x !0)
725                                 //
726                                 return this;
727                         }
728                 }
729
730                 readonly ParameterReference parameter;
731
732                 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
733                         : base (scope, par.Name, par.Type)
734                 {
735                         this.parameter = par;
736                 }
737
738                 public HoistedParameter (HoistedParameter hp, string name)
739                         : base (hp.storey, name, hp.parameter.Type)
740                 {
741                         this.parameter = hp.parameter;
742                 }
743
744                 public void EmitHoistingAssignment (EmitContext ec)
745                 {
746                         //
747                         // Remove hoisted redirection to emit assignment from original parameter
748                         //
749                         HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
750                         parameter.Parameter.HoistedVariableReference = null;
751
752                         Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
753                         if (a.Resolve (ec) != null)
754                                 a.EmitStatement (ec);
755
756                         parameter.Parameter.HoistedVariableReference = temp;
757                 }
758
759                 public override void EmitSymbolInfo ()
760                 {
761                         SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
762                 }
763
764                 public Field Field {
765                         get { return field; }
766                 }
767         }
768
769         class HoistedLocalVariable : HoistedVariable
770         {
771                 readonly string name;
772
773                 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
774                         : base (scope, name, local.VariableType)
775                 {
776                         this.name = local.Name;
777                 }
778
779                 public override void EmitSymbolInfo ()
780                 {
781                         SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
782                 }
783         }
784
785         public class HoistedThis : HoistedVariable
786         {
787                 readonly This this_reference;
788
789                 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
790                         : base (storey, "<>f__this", this_reference.Type)
791                 {
792                         this.this_reference = this_reference;
793                 }
794
795                 public void EmitHoistingAssignment (EmitContext ec)
796                 {
797                         SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
798                         if (a.Resolve (ec) != null)
799                                 a.EmitStatement (ec);
800                 }
801
802                 public override void EmitSymbolInfo ()
803                 {
804                         SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
805                 }
806
807                 public Field Field {
808                         get { return field; }
809                 }
810
811                 public void RemoveHoisting ()
812                 {
813                         this_reference.RemoveHoisting ();
814                 }
815         }
816
817         //
818         // Anonymous method expression as created by parser
819         //
820         public class AnonymousMethodExpression : Expression
821         {
822                 public readonly Parameters Parameters;
823                 ListDictionary compatibles;
824                 public ToplevelBlock Block;
825
826                 public AnonymousMethodExpression (Parameters parameters, Location loc)
827                 {
828                         this.Parameters = parameters;
829                         this.loc = loc;
830                         this.compatibles = new ListDictionary ();
831                 }
832
833                 public override string ExprClassName {
834                         get {
835                                 return "anonymous method";
836                         }
837                 }
838
839                 public virtual bool HasExplicitParameters {
840                         get {
841                                 return Parameters != null;
842                         }
843                 }
844
845                 //
846                 // Returns true if the body of lambda expression can be implicitly
847                 // converted to the delegate of type `delegate_type'
848                 //
849                 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
850                 {
851                         using (ec.Set (EmitContext.Flags.ProbingMode)) {
852                                 return Compatible (ec, delegate_type) != null;
853                         }
854                 }
855
856                 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
857                 {
858                         if (TypeManager.IsDelegateType (delegate_type))
859                                 return delegate_type;
860
861 #if GMCS_SOURCE
862                         if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
863                                 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
864                                 if (TypeManager.IsDelegateType (delegate_type))
865                                         return delegate_type;
866
867                                 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
868                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
869                                 return null;
870                         }
871 #endif
872
873                         Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
874                                       GetSignatureForError (), TypeManager.CSharpName (delegate_type));
875                         return null;
876                 }
877
878                 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
879                 {
880                         if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
881                                 return true;
882
883                         if (!ignore_error)
884                                 Report.Error (1661, loc,
885                                         "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
886                                         GetSignatureForError (), TypeManager.CSharpName (delegate_type));
887
888                         return false;
889                 }
890
891                 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
892                 {
893                         if (Parameters.Count != invoke_pd.Count) {
894                                 if (ignore_errors)
895                                         return false;
896                                 
897                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
898                                               TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
899                                 return false;
900                         }
901
902                         bool has_implicit_parameters = !HasExplicitParameters;
903                         bool error = false;
904
905                         for (int i = 0; i < Parameters.Count; ++i) {
906                                 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
907                                 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
908                                         if (ignore_errors)
909                                                 return false;
910                                         
911                                         if (p_mod == Parameter.Modifier.NONE)
912                                                 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
913                                                               (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
914                                         else
915                                                 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
916                                                               (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
917                                         error = true;
918                                 }
919
920                                 if (has_implicit_parameters)
921                                         continue;
922
923                                 Type type = invoke_pd.Types [i];
924                                 
925                                 // We assume that generic parameters are always inflated
926                                 if (TypeManager.IsGenericParameter (type))
927                                         continue;
928                                 
929                                 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
930                                         continue;
931                                 
932                                 if (invoke_pd.Types [i] != Parameters.Types [i]) {
933                                         if (ignore_errors)
934                                                 return false;
935                                         
936                                         Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
937                                                       (i+1).ToString (),
938                                                       TypeManager.CSharpName (Parameters.Types [i]),
939                                                       TypeManager.CSharpName (invoke_pd.Types [i]));
940                                         error = true;
941                                 }
942                         }
943
944                         return !error;
945                 }
946
947                 //
948                 // Infers type arguments based on explicit arguments
949                 //
950                 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
951                 {
952                         if (!HasExplicitParameters)
953                                 return false;
954
955                         if (!TypeManager.IsDelegateType (delegate_type)) {
956 #if GMCS_SOURCE
957                                 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
958                                         return false;
959
960                                 delegate_type = delegate_type.GetGenericArguments () [0];
961                                 if (!TypeManager.IsDelegateType (delegate_type))
962                                         return false;
963 #else
964                                 return false;
965 #endif
966                         }
967                         
968                         AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
969                         if (d_params.Count != Parameters.Count)
970                                 return false;
971
972                         for (int i = 0; i < Parameters.Count; ++i) {
973                                 Type itype = d_params.Types [i];
974                                 if (!TypeManager.IsGenericParameter (itype)) {
975                                         if (!TypeManager.HasElementType (itype))
976                                                 continue;
977                                         
978                                         if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
979                                             continue;
980                                 }
981                                 type_inference.ExactInference (Parameters.Types [i], itype);
982                         }
983                         return true;
984                 }
985
986                 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
987                 {
988                         AnonymousMethodBody am;
989                         using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
990                                 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
991                         }
992                         
993                         if (am == null)
994                                 return null;
995
996                         if (am.ReturnType == TypeManager.null_type)
997                                 am.ReturnType = null;
998
999                         return am.ReturnType;
1000                 }
1001
1002                 //
1003                 // Returns AnonymousMethod container if this anonymous method
1004                 // expression can be implicitly converted to the delegate type `delegate_type'
1005                 //
1006                 public Expression Compatible (EmitContext ec, Type type)
1007                 {
1008                         Expression am = (Expression) compatibles [type];
1009                         if (am != null)
1010                                 return am;
1011
1012                         Type delegate_type = CompatibleChecks (ec, type);
1013                         if (delegate_type == null)
1014                                 return null;
1015
1016                         //
1017                         // At this point its the first time we know the return type that is 
1018                         // needed for the anonymous method.  We create the method here.
1019                         //
1020
1021                         MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1022                                 ec.ContainerType, delegate_type);
1023                         Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1024
1025 #if MS_COMPATIBLE
1026                         Type[] g_args = delegate_type.GetGenericArguments ();
1027                         if (return_type.IsGenericParameter)
1028                                 return_type = g_args [return_type.GenericParameterPosition];
1029 #endif
1030
1031                         //
1032                         // Second: the return type of the delegate must be compatible with 
1033                         // the anonymous type.   Instead of doing a pass to examine the block
1034                         // we satisfy the rule by setting the return type on the EmitContext
1035                         // to be the delegate type return type.
1036                         //
1037
1038                         try {
1039                                 int errors = Report.Errors;
1040                                 am = CompatibleMethod (ec, null, return_type, delegate_type);
1041                                 if (am != null && delegate_type != type && errors == Report.Errors)
1042                                         am = CreateExpressionTree (ec, delegate_type);
1043
1044                                 if (!ec.IsInProbingMode)
1045                                         compatibles.Add (type, am);
1046
1047                                 return am;
1048                         } catch (Exception e) {
1049                                 throw new InternalErrorException (e, loc);
1050                         }
1051                 }
1052
1053                 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1054                 {
1055                         return CreateExpressionTree (ec);
1056                 }
1057
1058                 public override Expression CreateExpressionTree (EmitContext ec)
1059                 {
1060                         Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1061                         return null;
1062                 }
1063
1064                 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1065                 {
1066                         AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1067
1068                         if (Parameters == null) {
1069                                 //
1070                                 // We provide a set of inaccessible parameters
1071                                 //
1072                                 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1073
1074                                 for (int i = 0; i < delegate_parameters.Count; i++) {
1075                                         Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1076                                         if (i_mod == Parameter.Modifier.OUT) {
1077                                                 Report.Error (1688, loc, "Cannot convert anonymous " +
1078                                                                   "method block without a parameter list " +
1079                                                                   "to delegate type `{0}' because it has " +
1080                                                                   "one or more `out' parameters.",
1081                                                                   TypeManager.CSharpName (delegate_type));
1082                                                 return null;
1083                                         }
1084                                         fixedpars[i] = new Parameter (
1085                                                 null, null,
1086                                                 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1087                                 }
1088
1089                                 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1090                         }
1091
1092                         if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1093                                 return null;
1094                         }
1095
1096                         return Parameters;
1097                 }
1098
1099                 public override Expression DoResolve (EmitContext ec)
1100                 {
1101                         if (!ec.IsAnonymousMethodAllowed) {
1102                                 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1103                                 return null;
1104                         }
1105
1106                         //
1107                         // Set class type, set type
1108                         //
1109
1110                         eclass = ExprClass.Value;
1111
1112                         //
1113                         // This hack means `The type is not accessible
1114                         // anywhere', we depend on special conversion
1115                         // rules.
1116                         // 
1117                         type = TypeManager.anonymous_method_type;
1118
1119                         if ((Parameters != null) && !Parameters.Resolve (ec))
1120                                 return null;
1121
1122                         // FIXME: The emitted code isn't very careful about reachability
1123                         // so, ensure we have a 'ret' at the end
1124                         if (ec.CurrentBranching != null &&
1125                             ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1126                                 ec.NeedReturnLabel ();
1127
1128                         return this;
1129                 }
1130
1131                 public override void Emit (EmitContext ec)
1132                 {
1133                         // nothing, as we only exist to not do anything.
1134                 }
1135
1136                 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1137                 {
1138                         Report.Error (1686, loc,
1139                                 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1140                                 var.Name);
1141                 }
1142
1143                 public override string GetSignatureForError ()
1144                 {
1145                         return ExprClassName;
1146                 }
1147
1148                 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1149                 {
1150                         Parameters p = ResolveParameters (ec, tic, delegate_type);
1151                         if (p == null)
1152                                 return null;
1153
1154                         ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1155
1156                         AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1157                         if (!anonymous.Compatible (ec))
1158                                 return null;
1159
1160                         return anonymous;
1161                 }
1162
1163                 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1164                 {
1165                         return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1166                 }
1167
1168                 protected override void CloneTo (CloneContext clonectx, Expression t)
1169                 {
1170                         AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1171
1172                         target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1173                 }
1174         }
1175
1176         //
1177         // Abstract expression for any block which requires variables hoisting
1178         //
1179         public abstract class AnonymousExpression : Expression
1180         {
1181                 protected class AnonymousMethodMethod : Method
1182                 {
1183                         public readonly AnonymousExpression AnonymousMethod;
1184                         public readonly AnonymousMethodStorey Storey;
1185                         readonly string RealName;
1186
1187                         public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1188                                                           GenericMethod generic, TypeExpr return_type,
1189                                                           int mod, string real_name, MemberName name,
1190                                                           Parameters parameters)
1191                                 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1192                                                 name, parameters, null)
1193                         {
1194                                 this.AnonymousMethod = am;
1195                                 this.Storey = storey;
1196                                 this.RealName = real_name;
1197
1198                                 Parent.PartialContainer.AddMethod (this);
1199                                 Block = am.Block;
1200                         }
1201
1202                         public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1203                         {
1204                                 EmitContext aec = AnonymousMethod.aec;
1205                                 aec.ig = ig;
1206                                 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1207                                 return aec;
1208                         }
1209
1210                         public override bool Define ()
1211                         {
1212                                 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1213                                         AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1214                                         if (gstorey != null) {
1215                                                 if (!Parameters.IsEmpty) {
1216                                                         Type [] ptypes = Parameters.Types;
1217                                                         for (int i = 0; i < ptypes.Length; ++i)
1218                                                                 ptypes [i] = gstorey.MutateType (ptypes [i]);
1219                                                 }
1220
1221                                                 member_type = gstorey.MutateType (ReturnType);
1222                                         }
1223                                 }
1224
1225                                 return base.Define ();
1226                         }
1227
1228                         public override void Emit ()
1229                         {
1230                                 //
1231                                 // Before emitting any code we have to change all MVAR references to VAR
1232                                 // when the method is of generic type and has hoisted variables
1233                                 //
1234                                 if (Storey == Parent && Storey.IsGeneric) {
1235                                         AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1236                                         if (gstorey != null) {
1237                                                 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1238                                                 block.MutateHoistedGenericType (gstorey);
1239                                         }
1240                                 }
1241
1242                                 if (MethodBuilder == null) {
1243                                         Define ();
1244                                 }
1245
1246                                 base.Emit ();
1247                         }
1248
1249                         public override void EmitExtraSymbolInfo (SourceMethod source)
1250                         {
1251                                 source.SetRealMethodName (RealName);
1252                         }
1253                 }
1254
1255                 //
1256                 // The block that makes up the body for the anonymous method
1257                 //
1258                 protected readonly ToplevelBlock Block;
1259
1260                 public Type ReturnType;
1261                 protected EmitContext aec;
1262
1263                 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1264                 {
1265                         this.ReturnType = return_type;
1266                         this.Block = block;
1267                         this.loc = loc;
1268                 }
1269
1270                 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1271                 public abstract string ContainerType { get; }
1272                 public abstract bool IsIterator { get; }
1273                 public abstract AnonymousMethodStorey Storey { get; }
1274
1275                 public bool Compatible (EmitContext ec)
1276                 {
1277                         // TODO: Implement clone
1278                         aec = new EmitContext (
1279                                 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1280                                 Location, null, ReturnType,
1281                                 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1282
1283                         aec.CurrentAnonymousMethod = this;
1284                         aec.IsStatic = ec.IsStatic;
1285
1286                         IDisposable aec_dispose = null;
1287                         EmitContext.Flags flags = 0;
1288                         if (ec.InferReturnType)
1289                                 flags |= EmitContext.Flags.InferReturnType;
1290
1291                         if (ec.IsInProbingMode)
1292                                 flags |= EmitContext.Flags.ProbingMode;
1293
1294                         if (ec.IsInFieldInitializer)
1295                                 flags |= EmitContext.Flags.InFieldInitializer;
1296
1297                         if (ec.IsInUnsafeScope)
1298                                 flags |= EmitContext.Flags.InUnsafe;
1299
1300                         // HACK: Flag with 0 cannot be set 
1301                         if (flags != 0)
1302                                 aec_dispose = aec.Set (flags);
1303
1304                         bool unreachable;
1305                         bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1306
1307                         if (ec.InferReturnType)
1308                                 ReturnType = aec.ReturnType;
1309
1310                         if (aec_dispose != null) {
1311                                 aec_dispose.Dispose ();
1312                         }
1313
1314                         return res;
1315                 }
1316         }
1317
1318         public class AnonymousMethodBody : AnonymousExpression
1319         {
1320                 ArrayList referenced_storeys;
1321                 protected readonly Parameters parameters;
1322                 AnonymousMethodStorey storey;
1323
1324                 AnonymousMethodMethod method;
1325                 Field am_cache;
1326
1327                 static int unique_id;
1328
1329                 public AnonymousMethodBody (Parameters parameters,
1330                                         ToplevelBlock block, Type return_type, Type delegate_type,
1331                                         Location loc)
1332                         : base (block, return_type, loc)
1333                 {
1334                         this.type = delegate_type;
1335                         this.parameters = parameters;
1336                 }
1337
1338                 public override string ContainerType {
1339                         get { return "anonymous method"; }
1340                 }
1341
1342                 public override AnonymousMethodStorey Storey {
1343                         get { return storey; }
1344                 }
1345
1346                 public override bool IsIterator {
1347                         get { return false; }
1348                 }
1349
1350                 //
1351                 // Adds new storey reference to track out of scope variables
1352                 //
1353                 public override void AddStoreyReference (AnonymousMethodStorey storey)
1354                 {
1355                         if (referenced_storeys == null) {
1356                                 referenced_storeys = new ArrayList (2);
1357                         } else {
1358                                 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1359                                         if (ams == storey)
1360                                                 return;
1361                                 }
1362                         }
1363
1364                         referenced_storeys.Add (storey);
1365                 }
1366
1367                 public override Expression CreateExpressionTree (EmitContext ec)
1368                 {
1369                         Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1370                         return null;
1371                 }
1372
1373                 bool Define (EmitContext ec)
1374                 {
1375                         if (aec == null && !Compatible (ec))
1376                                 return false;
1377
1378                         if (referenced_storeys != null)
1379                                 ConnectReferencedStoreys ();
1380
1381                         return true;
1382                 }
1383
1384                 void ConnectReferencedStoreys ()
1385                 {
1386                         storey = FindBestMethodStorey ();
1387
1388                         foreach (AnonymousMethodStorey s in referenced_storeys) {
1389                                 //
1390                                 // An anonymous method has to have an instance access when
1391                                 // children anonymous method requires access to parent storey
1392                                 // hoisted variables
1393                                 //
1394                                 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1395                                         b.Toplevel.HasStoreyAccess = true;
1396
1397                                 if (s == storey)
1398                                         continue;
1399
1400                                 s.HasHoistedVariables = true;
1401                                 Block.Parent.Explicit.PropagateStoreyReference (s);
1402                         }
1403                 }
1404
1405                 //
1406                 // Creates a host for the anonymous method
1407                 //
1408                 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1409                 {
1410                         //
1411                         // Anonymous method body can be converted to
1412                         //
1413                         // 1, an instance method in current scope when only `this' is hoisted
1414                         // 2, a static method in current scope when neither `this' nor any variable is hoisted
1415                         // 3, an instance method in compiler generated storey when any hoisted variable exists
1416                         //
1417
1418                         int modifiers;
1419                         if (referenced_storeys != null || Block.HasStoreyAccess) {
1420                                 if (storey == null || storey.IsUndone)
1421                                         storey = FindBestMethodStorey ();
1422
1423                                 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1424                         } else {
1425                                 if (ec.CurrentAnonymousMethod != null)
1426                                         storey = ec.CurrentAnonymousMethod.Storey;
1427
1428                                 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1429                         }
1430
1431                         DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1432
1433                         MemberCore mc = ec.ResolveContext as MemberCore;
1434                         string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1435                                 "m", null, unique_id++);
1436
1437                         MemberName member_name;
1438                         GenericMethod generic_method;
1439                         if (storey == null && mc.MemberName.IsGeneric) {
1440                                 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1441
1442                                 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1443                                         new TypeExpression (ReturnType, Location), parameters);
1444
1445                                 ArrayList list = new ArrayList ();
1446                                 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1447                                         if (tparam.Constraints != null)
1448                                                 list.Add (tparam.Constraints.Clone ());
1449                                 }
1450                                 generic_method.SetParameterInfo (list);
1451                         } else {
1452                                 member_name = new MemberName (name, Location);
1453                                 generic_method = null;
1454                         }
1455
1456                         string real_name = String.Format (
1457                                 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1458                                 parameters.GetSignatureForError ());
1459
1460                         return new AnonymousMethodMethod (parent,
1461                                 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1462                                 real_name, member_name, parameters);
1463                 }
1464
1465                 public override Expression DoResolve (EmitContext ec)
1466                 {
1467                         if (eclass == ExprClass.Invalid) {
1468                                 if (!Define (ec))
1469                                         return null;
1470                         }
1471
1472                         eclass = ExprClass.Value;
1473                         return this;
1474                 }
1475
1476                 public override void Emit (EmitContext ec)
1477                 {
1478                         //
1479                         // Use same anonymous method implementation for scenarios where same
1480                         // code is used from multiple blocks, e.g. field initializers
1481                         //
1482                         if (method == null) {
1483                                 //
1484                                 // Delay an anonymous method definition to avoid emitting unused code
1485                                 // for unreachable blocks or expression trees
1486                                 //
1487                                 method = DoCreateMethodHost (ec);
1488                                 method.Define ();
1489                         }
1490
1491                         bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1492                         if (is_static && am_cache == null) {
1493                                 //
1494                                 // Creates a field cache to store delegate instance if it's not generic
1495                                 //
1496                                 if (!method.MemberName.IsGeneric) {
1497                                         TypeContainer parent = method.Parent.PartialContainer;
1498                                         int id = parent.Fields == null ? 0 : parent.Fields.Count;
1499                                         am_cache = new Field (parent, new TypeExpression (type, loc),
1500                                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1501                                                 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1502                                         am_cache.Define ();
1503                                         parent.AddField (am_cache);
1504                                 } else {
1505                                         // TODO: Implement caching of generated generic static methods
1506                                         //
1507                                         // Idea:
1508                                         //
1509                                         // Some extra class is needed to capture variable generic type
1510                                         // arguments. Maybe we could re-use anonymous types, with a unique
1511                                         // anonymous method id, but they are quite heavy.
1512                                         //
1513                                         // Consider : "() => typeof(T);"
1514                                         //
1515                                         // We need something like
1516                                         // static class Wrap<Tn, Tm, DelegateType> {
1517                                         //              public static DelegateType cache;
1518                                         // }
1519                                         //
1520                                         // We then specialize local variable to capture all generic parameters
1521                                         // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1522                                         //
1523                                 }
1524                         }
1525
1526                         ILGenerator ig = ec.ig;
1527                         Label l_initialized = ig.DefineLabel ();
1528
1529                         if (am_cache != null) {
1530                                 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1531                                 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1532                         }
1533
1534                         //
1535                         // Load method delegate implementation
1536                         //
1537
1538                         if (is_static) {
1539                                 ig.Emit (OpCodes.Ldnull);
1540                         } else if (storey != null) {
1541                                 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1542                                 if (e != null)
1543                                         e.Emit (ec);
1544                         } else {
1545                                 ig.Emit (OpCodes.Ldarg_0);
1546                         }
1547
1548                         MethodInfo delegate_method = method.MethodBuilder;
1549 #if GMCS_SOURCE
1550                         if (storey != null && storey.MemberName.IsGeneric) {
1551                                 Type t = storey.Instance.Type;
1552                                 
1553                                 //
1554                                 // Mutate anonymous method instance type if we are in nested
1555                                 // hoisted generic anonymous method storey
1556                                 //
1557                                 if (ec.CurrentAnonymousMethod != null &&
1558                                         ec.CurrentAnonymousMethod.Storey != null &&
1559                                         ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1560                                         t = storey.GetGenericStorey ().MutateType (t);
1561                                 }
1562
1563                                 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1564                         }
1565 #endif
1566                         ig.Emit (OpCodes.Ldftn, delegate_method);
1567
1568                         ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1569 #if MS_COMPATIBLE
1570             if (type.IsGenericType && type is TypeBuilder)
1571                 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1572 #endif
1573                         ig.Emit (OpCodes.Newobj, constructor_method);
1574
1575                         if (am_cache != null) {
1576                                 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1577                                 ig.MarkLabel (l_initialized);
1578                                 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1579                         }
1580                 }
1581
1582                 //
1583                 // Look for the best storey for this anonymous method
1584                 //
1585                 AnonymousMethodStorey FindBestMethodStorey ()
1586                 {
1587                         //
1588                         // Use the nearest parent block which has a storey
1589                         //
1590                         for (Block b = Block.Parent; b != null; b = b.Parent) {
1591                                 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1592                                 if (s != null)
1593                                         return s;
1594                         }
1595                                         
1596                         return null;
1597                 }
1598
1599                 public override string GetSignatureForError ()
1600                 {
1601                         return TypeManager.CSharpName (type);
1602                 }
1603
1604                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1605                 {
1606                         type = storey.MutateType (type);
1607                 }
1608
1609                 public static void Reset ()
1610                 {
1611                         unique_id = 0;
1612                 }
1613         }
1614
1615         //
1616         // Anonymous type container
1617         //
1618         public class AnonymousTypeClass : CompilerGeneratedClass
1619         {
1620                 static int types_counter;
1621                 public const string ClassNamePrefix = "<>__AnonType";
1622                 public const string SignatureForError = "anonymous type";
1623                 
1624                 readonly ArrayList parameters;
1625
1626                 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1627                         : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1628                 {
1629                         this.parameters = parameters;
1630                 }
1631
1632                 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1633                 {
1634                         if (RootContext.Version <= LanguageVersion.ISO_2)
1635                                 Report.FeatureIsNotAvailable (loc, "anonymous types");
1636
1637                         string name = ClassNamePrefix + types_counter++;
1638
1639                         SimpleName [] t_args = new SimpleName [parameters.Count];
1640                         TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1641                         Parameter [] ctor_params = new Parameter [parameters.Count];
1642                         for (int i = 0; i < parameters.Count; ++i) {
1643                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1644
1645                                 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1646                                 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1647                                 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1648                         }
1649
1650                         //
1651                         // Create generic anonymous type host with generic arguments
1652                         // named upon properties names
1653                         //
1654                         AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1655                                 new MemberName (name, new TypeArguments (loc, t_params), loc), parameters, loc);
1656
1657                         if (parameters.Count > 0)
1658                                 a_type.SetParameterInfo (null);
1659
1660                         Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1661                                 null, new Parameters (ctor_params), null, loc);
1662                         c.Block = new ToplevelBlock (c.Parameters, loc);
1663
1664                         // 
1665                         // Create fields and contructor body with field initialization
1666                         //
1667                         bool error = false;
1668                         for (int i = 0; i < parameters.Count; ++i) {
1669                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1670
1671                                 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1672                                         new MemberName ("<" + p.Name + ">", p.Location), null);
1673
1674                                 if (!a_type.AddField (f)) {
1675                                         error = true;
1676                                         Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1677                                                 p.Name);
1678                                         continue;
1679                                 }
1680
1681                                 c.Block.AddStatement (new StatementExpression (
1682                                         new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1683                                                 c.Block.GetParameterReference (p.Name, p.Location))));
1684
1685                                 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1686                                 get_block.AddStatement (new Return (
1687                                         new MemberAccess (new This (p.Location), f.Name), p.Location));
1688                                 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1689                                 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1690                                         new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1691                                 a_type.AddProperty (prop);
1692                         }
1693
1694                         if (error)
1695                                 return null;
1696
1697                         a_type.AddConstructor (c);
1698                         return a_type;
1699                 }
1700                 
1701                 public static void Reset ()
1702                 {
1703                         types_counter = 0;
1704                 }
1705
1706                 protected override bool AddToContainer (MemberCore symbol, string name)
1707                 {
1708                         MemberCore mc = (MemberCore) defined_names [name];
1709
1710                         if (mc == null) {
1711                                 defined_names.Add (name, symbol);
1712                                 return true;
1713                         }
1714
1715                         Report.SymbolRelatedToPreviousError (mc);
1716                         return false;
1717                 }
1718
1719                 void DefineOverrides ()
1720                 {
1721                         Location loc = Location;
1722
1723                         Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1724                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1725                                 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1726
1727                         Method tostring = new Method (this, null, TypeManager.system_string_expr,
1728                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1729                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1730
1731                         ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1732                         TypeExpr current_type;
1733                         if (IsGeneric)
1734                                 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1735                         else
1736                                 current_type = new TypeExpression (TypeBuilder, loc);
1737
1738                         equals_block.AddVariable (current_type, "other", loc);
1739                         LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1740
1741                         MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1742                                 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1743
1744                         Expression rs_equals = null;
1745                         Expression string_concat = new StringConstant ("<empty type>", loc);
1746                         Expression rs_hashcode = new IntConstant (-2128831035, loc);
1747                         for (int i = 0; i < parameters.Count; ++i) {
1748                                 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1749                                 Field f = (Field) Fields [i];
1750
1751                                 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1752                                         system_collections_generic, "EqualityComparer",
1753                                                 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1754                                                 "Default", loc);
1755
1756                                 ArrayList arguments_equal = new ArrayList (2);
1757                                 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1758                                 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1759
1760                                 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1761                                         "Equals", loc), arguments_equal);
1762
1763                                 ArrayList arguments_hashcode = new ArrayList (1);
1764                                 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1765                                 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1766                                         "GetHashCode", loc), arguments_hashcode);
1767
1768                                 IntConstant FNV_prime = new IntConstant (16777619, loc);                                
1769                                 rs_hashcode = new Binary (Binary.Operator.Multiply,
1770                                         new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1771                                         FNV_prime);
1772
1773                                 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1774                                         new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1775                                         new Invocation (new MemberAccess (
1776                                                 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1777                                         new StringConstant ("<null>", loc));
1778
1779                                 if (rs_equals == null) {
1780                                         rs_equals = field_equal;
1781                                         string_concat = new Binary (Binary.Operator.Addition,
1782                                                 new StringConstant (p.Name + " = ", loc),
1783                                                 field_to_string);
1784                                         continue;
1785                                 }
1786
1787                                 //
1788                                 // Implementation of ToString () body using string concatenation
1789                                 //                              
1790                                 string_concat = new Binary (Binary.Operator.Addition,
1791                                         new Binary (Binary.Operator.Addition,
1792                                                 string_concat,
1793                                                 new StringConstant (", " + p.Name + " = ", loc)),
1794                                         field_to_string);
1795
1796                                 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1797                         }
1798
1799                         //
1800                         // Equals (object obj) override
1801                         //
1802                         equals_block.AddStatement (new StatementExpression (
1803                                 new SimpleAssign (other_variable,
1804                                         new As (equals_block.GetParameterReference ("obj", loc),
1805                                                 current_type, loc), loc)));
1806
1807                         Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1808                         if (rs_equals != null)
1809                                 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1810                         equals_block.AddStatement (new Return (equals_test, loc));
1811
1812                         equals.Block = equals_block;
1813                         equals.Define ();
1814                         AddMethod (equals);
1815
1816                         //
1817                         // GetHashCode () override
1818                         //
1819                         Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1820                                 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1821                                 new MemberName ("GetHashCode", loc),
1822                                 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1823
1824                         //
1825                         // Modified FNV with good avalanche behavior and uniform
1826                         // distribution with larger hash sizes.
1827                         //
1828                         // const int FNV_prime = 16777619;
1829                         // int hash = (int) 2166136261;
1830                         // foreach (int d in data)
1831                         //     hash = (hash ^ d) * FNV_prime;
1832                         // hash += hash << 13;
1833                         // hash ^= hash >> 7;
1834                         // hash += hash << 3;
1835                         // hash ^= hash >> 17;
1836                         // hash += hash << 5;
1837
1838                         ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1839                         hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1840                         LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1841                         hashcode_block.AddStatement (new StatementExpression (
1842                                 new SimpleAssign (hash_variable, rs_hashcode)));
1843
1844                         hashcode_block.AddStatement (new StatementExpression (
1845                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1846                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1847                         hashcode_block.AddStatement (new StatementExpression (
1848                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1849                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1850                         hashcode_block.AddStatement (new StatementExpression (
1851                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1852                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1853                         hashcode_block.AddStatement (new StatementExpression (
1854                                 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1855                                         new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1856                         hashcode_block.AddStatement (new StatementExpression (
1857                                 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1858                                         new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1859
1860                         hashcode_block.AddStatement (new Return (hash_variable, loc));
1861                         hashcode.Block = hashcode_block;
1862                         hashcode.Define ();
1863                         AddMethod (hashcode);
1864
1865                         //
1866                         // ToString () override
1867                         //
1868
1869                         ToplevelBlock tostring_block = new ToplevelBlock (loc);
1870                         tostring_block.AddStatement (new Return (string_concat, loc));
1871                         tostring.Block = tostring_block;
1872                         tostring.Define ();
1873                         AddMethod (tostring);
1874                 }
1875
1876                 public override bool Define ()
1877                 {
1878                         if (base.Define ())
1879                                 DefineOverrides ();
1880
1881                         return true;
1882                 }
1883
1884                 public override string GetSignatureForError ()
1885                 {
1886                         return SignatureForError;
1887                 }
1888
1889                 public ArrayList Parameters {
1890                         get {
1891                                 return parameters;
1892                         }
1893                 }
1894         }
1895 }