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