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