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