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