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