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