2005-07-06 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / anonymous.cs
1 //
2 // anonymous.cs: Support for anonymous methods
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximain.com)
6 //
7 // (C) 2003, 2004 Novell, Inc.
8 //
9 // TODO: Ideally, we should have the helper classes emited as a hierarchy to map
10 // their nesting, and have the visibility set to private, instead of NestedAssembly
11 //
12 //
13 //
14
15 using System;
16 using System.Text;
17 using System.Collections;
18 using System.Reflection;
19 using System.Reflection.Emit;
20
21 namespace Mono.CSharp {
22
23         public abstract class AnonymousContainer : Expression
24         {
25                 // Used to generate unique method names.
26                 protected static int anonymous_method_count;
27                     
28                 // An array list of AnonymousMethodParameter or null
29                 public Parameters Parameters;
30                 
31                 //
32                 // The block that makes up the body for the anonymous mehtod
33                 //
34                 public ToplevelBlock Block;
35
36                 //
37                 // The container block for this anonymous method.
38                 //
39                 public Block ContainingBlock;
40
41                 //
42                 // The implicit method we create
43                 //
44                 public Method method;
45
46                 protected MethodInfo invoke_mb;
47                 
48                 // The emit context for the anonymous method
49                 public EmitContext aec;
50                 public InternalParameters amp;
51                 public string[] TypeParameters;
52                 public Type[] TypeArguments;
53                 protected bool unreachable;
54                 
55                 //
56                 // The modifiers applied to the method, we aggregate them
57                 //
58                 protected int method_modifiers = Modifiers.PRIVATE;
59                 
60                 //
61                 // During the resolve stage of the anonymous method body,
62                 // we discover the actual scope where we are hosted, or
63                 // null to host the method in the same class
64                 //
65                 public ScopeInfo Scope;
66
67                 //
68                 // Points to our container anonymous method if its present
69                 //
70                 public AnonymousContainer ContainerAnonymousMethod;     
71
72                 protected AnonymousContainer (Parameters parameters, ToplevelBlock container,
73                                               ToplevelBlock block, Location l)
74                 {
75                         Parameters = parameters;
76                         Block = block;
77                         loc = l;
78
79                         //
80                         // The order is important: this setups the CaptureContext tree hierarchy.
81                         //
82                         container.SetHaveAnonymousMethods (l, this);
83                         block.SetHaveAnonymousMethods (l, this);
84                 }
85
86                 protected AnonymousContainer (Parameters parameters, ToplevelBlock container,
87                                               Location l)
88                 {
89                         Parameters = parameters;
90                         Block = new ToplevelBlock (container, Parameters, l);
91                         loc = l;
92
93                         //
94                         // The order is important: this setups the CaptureContext tree hierarchy.
95                         //
96                         container.SetHaveAnonymousMethods (loc, this);
97                         Block.SetHaveAnonymousMethods (loc, this);
98                 }
99
100                 public override Expression DoResolve (EmitContext ec)
101                 {
102                         //
103                         // Set class type, set type
104                         //
105
106                         eclass = ExprClass.Value;
107
108                         //
109                         // This hack means `The type is not accessible
110                         // anywhere', we depend on special conversion
111                         // rules.
112                         // 
113                         type = TypeManager.anonymous_method_type;
114
115                         return this;
116                 }
117
118                 protected abstract bool CreateMethodHost (EmitContext ec);
119
120                 public abstract void CreateScopeType (EmitContext ec, ScopeInfo scope);
121
122                 public abstract Iterator Iterator {
123                         get;
124                 }
125
126                 public abstract bool IsIterator {
127                         get;
128                 }
129         }
130
131         public class AnonymousMethod : AnonymousContainer
132         {
133                 public AnonymousMethod (Parameters parameters, ToplevelBlock container,
134                                         ToplevelBlock block, Location l)
135                         : base (parameters, container, block, l)
136                 {
137                 }
138
139                 public override Iterator Iterator {
140                         get { return null; }
141                 }
142
143                 public override bool IsIterator {
144                         get { return false; }
145                 }
146
147                 public override void Emit (EmitContext ec)
148                 {
149                         // nothing, as we only exist to not do anything.
150                 }
151
152                 //
153                 // Creates the host for the anonymous method
154                 //
155                 protected override bool CreateMethodHost (EmitContext ec)
156                 {
157                         //
158                         // Crude hack follows: we replace the TypeBuilder during the
159                         // definition to get the method hosted in the right class
160                         //
161                         
162                         TypeBuilder current_type = ec.TypeContainer.TypeBuilder;
163                         TypeBuilder type_host = (Scope == null ) // || Scope.ScopeTypeBuilder == null)
164                                 ? current_type : Scope.ScopeTypeBuilder;
165
166                         if (current_type == null)
167                                 throw new Exception ("The current_type is null");
168                         
169                         if (type_host == null)
170                                 throw new Exception (String.Format ("Type host is null, Scope is {0}", Scope == null ? "null" : "Not null"));
171                         
172                         if (current_type == type_host && ec.IsStatic){
173                                 if (ec.IsStatic){
174                                         method_modifiers |= Modifiers.STATIC;
175                                 }
176                                 current_type = null;
177                         } 
178
179                         string name = "<#AnonymousMethod>" + anonymous_method_count++;
180                         MemberName member_name;
181
182                         GenericMethod generic_method = null;
183                         if (TypeParameters != null) {
184                                 TypeArguments args = new TypeArguments (loc);
185                                 foreach (string t in TypeParameters)
186                                         args.Add (new SimpleName (t, loc));
187
188                                 member_name = new MemberName (name, args);
189
190                                 generic_method = new GenericMethod (
191                                         ec.DeclSpace.NamespaceEntry,
192                                         (TypeContainer) ec.TypeContainer,
193                                         member_name, loc);
194
195                                 generic_method.SetParameterInfo (null);
196                         } else
197                                 member_name = new MemberName (name);
198
199                         method = new Method (
200                                 (TypeContainer) ec.TypeContainer, generic_method,
201                                 new TypeExpression (invoke_mb.ReturnType, loc),
202                                 method_modifiers, false, member_name,
203                                 Parameters, null, loc);
204                         method.Block = Block;
205
206                         //
207                         // Swap the TypeBuilder while we define the method, then restore
208                         //
209                         if (current_type != null)
210                                 ec.TypeContainer.TypeBuilder = type_host;
211                         bool res = method.Define ();
212                         if (current_type != null)
213                                 ec.TypeContainer.TypeBuilder = current_type;
214
215                         return res;
216                 }
217                 
218                 void Error_ParameterMismatch (Type t)
219                 {
220                         Report.Error (1661, loc, "Anonymous method could not be converted to delegate `" +
221                                       "{0}' since there is a parameter mismatch", t);
222         }
223
224                 //
225                 // Returns true if this anonymous method can be implicitly
226                 // converted to the delegate type `delegate_type'
227                 //
228                 public Expression Compatible (EmitContext ec, Type delegate_type, bool probe)
229                 {
230                         //
231                         // At this point its the first time we know the return type that is 
232                         // needed for the anonymous method.  We create the method here.
233                         //
234
235                         MethodGroupExpr invoke_mg = Delegate.GetInvokeMethod (ec, delegate_type, loc);
236                         invoke_mb = (MethodInfo) invoke_mg.Methods [0];
237                         ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
238
239                         if (delegate_type.IsGenericInstance) {
240                                 TypeArguments = TypeManager.GetTypeArguments (delegate_type);
241
242                                 Type def = delegate_type.GetGenericTypeDefinition ();
243                                 Type[] tparam = TypeManager.GetTypeArguments (def);
244                                 TypeParameters = new string [tparam.Length];
245                                 for (int i = 0; i < tparam.Length; i++)
246                                         TypeParameters [i] = tparam [i].Name;
247                         }
248
249                         if (Parameters == null){
250                                 int i, j;
251                                 
252                                 //
253                                 // We provide a set of inaccessible parameters
254                                 //
255                                 int params_idx = -1;
256                                 for (i = 0; i < invoke_pd.Count; i++){
257                                         if (invoke_pd.ParameterModifier (i) == Parameter.Modifier.PARAMS)
258                                                 params_idx = i;
259                                 }
260                                 int n = invoke_pd.Count - (params_idx != -1 ? 1 : 0);
261                                 Parameter [] fixedpars = new Parameter [n];
262                                 
263                                 for (i =  j = 0; i < invoke_pd.Count; i++){
264                                         if (invoke_pd.ParameterModifier (i) == Parameter.Modifier.PARAMS)
265                                                 continue;
266                                         fixedpars [j] = new Parameter (
267                                                 new TypeExpression (invoke_pd.ParameterType (i), loc),
268                                                 "+" + j, invoke_pd.ParameterModifier (i), null, loc);
269                                         j++;
270                                 }
271                                 
272                                 Parameter variable = null;
273                                 if (params_idx != -1){
274                                         variable = new Parameter (
275                                                 new TypeExpression (invoke_pd.ParameterType (params_idx), loc),
276                                                 "+" + params_idx, invoke_pd.ParameterModifier (params_idx), null, loc);
277                                 }
278
279                                 Parameters = new Parameters (fixedpars, variable);
280                         }
281                         
282                         //
283                         // First, parameter types of `delegate_type' must be compatible
284                         // with the anonymous method.
285                         //
286                         amp = new InternalParameters (Parameters.GetParameterInfo (ec), Parameters);
287                         
288                         if (amp.Count != invoke_pd.Count){
289                                 if (!probe){
290                                         Report.Error (1593, loc, 
291                                               "Anonymous method has {0} parameters, while delegate requires {1}",
292                                               amp.Count, invoke_pd.Count);
293                                         Error_ParameterMismatch (delegate_type);
294                                 }
295                                 return null;
296                         }
297                         
298                         for (int i = 0; i < amp.Count; i++){
299                                 Parameter.Modifier amp_mod = amp.ParameterModifier (i);
300
301                                 if ((amp_mod & (Parameter.Modifier.OUT | Parameter.Modifier.REF)) != 0){
302                                         if (!probe){
303                                                 Error_ParameterMismatch (delegate_type);
304                                                 Report.Error (1677, loc, "Parameter '{0}' should not be declared with the '{1}' keyword", 
305                                                         i+1, amp.ModifierDesc (i));
306                                         }
307                                         return null;
308                                 }
309
310                                 if (amp_mod != invoke_pd.ParameterModifier (i)){
311                                         if (!probe){
312                                                 Report.Error (1676, loc, 
313                                                       "Signature mismatch in parameter modifier for parameter #0", i + 1);
314                                                 Error_ParameterMismatch (delegate_type);
315                                         }
316                                         return null;
317                                 }
318                                 
319                                 if (amp.ParameterType (i) != invoke_pd.ParameterType (i)){
320                                         if (!probe){
321                                                 Report.Error (1678, loc, 
322                                                                       "Signature mismatch in parameter {0}: need `{1}' got `{2}'", i + 1,
323                                                                       TypeManager.CSharpName (invoke_pd.ParameterType (i)),
324                                                                       TypeManager.CSharpName (amp.ParameterType (i)));
325                                                 Error_ParameterMismatch (delegate_type);
326                                         }
327                                         return null;
328                                 }
329                         }
330
331                         //
332                         // If we are only probing, return ourselves
333                         //
334                         if (probe)
335                                 return this;
336                         
337                         //
338                         // Second: the return type of the delegate must be compatible with 
339                         // the anonymous type.   Instead of doing a pass to examine the block
340                         // we satisfy the rule by setting the return type on the EmitContext
341                         // to be the delegate type return type.
342                         //
343
344                         //MethodBuilder builder = method_data.MethodBuilder;
345                         //ILGenerator ig = builder.GetILGenerator ();
346
347                         
348                         aec = new EmitContext (
349                                 ec.TypeContainer, ec.DeclSpace, loc, null,
350                                 invoke_mb.ReturnType,
351                                 /* REVIEW */ (ec.InIterator ? Modifiers.METHOD_YIELDS : 0) |
352                                 (ec.InUnsafe ? Modifiers.UNSAFE : 0) |
353                                 (ec.IsStatic ? Modifiers.STATIC : 0),
354                                 /* No constructor */ false);
355
356                         aec.CurrentAnonymousMethod = this;
357                         ContainerAnonymousMethod = ec.CurrentAnonymousMethod;
358                         ContainingBlock = ec.CurrentBlock;
359
360                         if (aec.ResolveTopBlock (ec, Block, amp, loc, out unreachable))
361                                 return new AnonymousDelegate (this, delegate_type, loc).Resolve (ec);
362
363                         return null;
364                 }
365
366                 public MethodInfo GetMethodBuilder ()
367                 {
368                         MethodInfo builder = method.MethodData.MethodBuilder;
369                         if (TypeArguments != null)
370                                 return builder.BindGenericParameters (TypeArguments);
371                         else
372                                 return builder;
373                 }
374                 
375                 public bool EmitMethod (EmitContext ec)
376                 {
377                         if (!CreateMethodHost (ec))
378                                 return false;
379
380                         MethodBuilder builder = method.MethodData.MethodBuilder;
381                         ILGenerator ig = builder.GetILGenerator ();
382                         aec.ig = ig;
383
384                         Parameters.LabelParameters (aec, builder);
385
386                         //
387                         // Adjust based on the computed state of the
388                         // method from CreateMethodHost
389                         
390                         aec.MethodIsStatic = (method_modifiers & Modifiers.STATIC) != 0;
391                         
392                         aec.EmitMeta (Block, amp);
393                         aec.EmitResolvedTopBlock (Block, unreachable);
394                         return true;
395                 }
396
397                 public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
398                 {
399                         TypeBuilder container = ec.TypeContainer.TypeBuilder;
400                         string name = String.Format ("<>AnonHelp<{0}>", scope.id);
401
402                         scope.ScopeTypeBuilder = container.DefineNestedType (
403                                 name, TypeAttributes.AutoLayout | TypeAttributes.Class |
404                                 TypeAttributes.NestedAssembly, TypeManager.object_type, null);
405
406                         Type [] constructor_types = TypeManager.NoTypes;
407                         Parameters constructor_parameters = Parameters.EmptyReadOnlyParameters;
408                         scope.ScopeConstructor = scope.ScopeTypeBuilder.DefineConstructor (
409                                 MethodAttributes.Public | MethodAttributes.HideBySig |
410                                 MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
411                                 CallingConventions.HasThis, constructor_types);
412                         InternalParameters parameter_info = new InternalParameters (constructor_types, constructor_parameters);
413                         TypeManager.RegisterMethod (scope.ScopeConstructor, parameter_info, constructor_types);
414
415                         ILGenerator cig = scope.ScopeConstructor.GetILGenerator ();
416                         cig.Emit (OpCodes.Ldarg_0);
417                         cig.Emit (OpCodes.Call, TypeManager.object_ctor);
418                         cig.Emit (OpCodes.Ret);
419                 }
420
421                 public static void Error_AddressOfCapturedVar (string name, Location loc)
422                 {
423                         Report.Error (1686, loc,
424                                       "Variable {0} is captured in an anonymous method and its address is also being taken: they are exclusive", name);
425                 }
426         }
427
428         //
429         // This will emit the code for the delegate, as well delegate creation on the host
430         //
431         public class AnonymousDelegate : DelegateCreation {
432                 AnonymousMethod am;
433
434                 public AnonymousDelegate (AnonymousMethod am, Type target_type, Location l)
435                 {
436                         type = target_type;
437                         loc = l;
438                         this.am = am;
439                 }
440
441                 public override Expression DoResolve (EmitContext ec)
442                 {
443                         eclass = ExprClass.Value;
444
445                         return this;
446                 }
447                 
448                 public override void Emit (EmitContext ec)
449                 {
450                         if (!am.EmitMethod (ec))
451                                 return;
452
453                         //
454                         // Now emit the delegate creation.
455                         //
456                         if ((am.method.ModFlags & Modifiers.STATIC) == 0)
457                                 delegate_instance_expression = new AnonymousInstance (am);
458                         
459                         Expression ml = Expression.MemberLookup (ec, type, ".ctor", loc);
460                         constructor_method = ((MethodGroupExpr) ml).Methods [0];
461                         delegate_method = am.GetMethodBuilder ();
462                         base.Emit (ec);
463                 }
464
465                 class AnonymousInstance : Expression {
466                         AnonymousMethod am;
467                         
468                         public AnonymousInstance (AnonymousMethod am)
469                         {
470                                 this.am = am;
471                                 eclass = ExprClass.Value;
472                         }
473
474                         public override Expression DoResolve (EmitContext ec)
475                         {
476                                 return this;
477                         }
478                         
479                         public override void Emit (EmitContext ec)
480                         {
481                                 am.aec.EmitMethodHostInstance (ec, am);
482                         }
483                 }
484         }
485
486         class CapturedParameter {
487                 public Type Type;
488                 public FieldBuilder FieldBuilder;
489                 public int Idx;
490
491                 public CapturedParameter (Type type, int idx)
492                 {
493                         Type = type;
494                         Idx = idx;
495                 }
496         }
497
498         //
499         // Here we cluster all the variables captured on a given scope, we also
500         // keep some extra information that might be required on each scope.
501         //
502         public class ScopeInfo {
503                 public CaptureContext CaptureContext;
504                 public ScopeInfo ParentScope;
505                 public Block ScopeBlock;
506                 public bool NeedThis = false;
507                 public bool HostsParameters = false;
508                 
509                 // For tracking the number of scopes created.
510                 public int id;
511                 static int count;
512                 bool inited = false;
513                 
514                 ArrayList locals = new ArrayList ();
515                 ArrayList children = new ArrayList ();
516
517                 //
518                 // The types and fields generated
519                 //
520                 public TypeBuilder ScopeTypeBuilder;
521                 public ConstructorBuilder ScopeConstructor;
522                 public FieldBuilder THIS;
523                 public FieldBuilder ParentLink;
524
525                 //
526                 // Points to the object of type `ScopeTypeBuilder' that
527                 // holds the data for the scope
528                 //
529                 LocalBuilder scope_instance;
530                 
531                 public ScopeInfo (CaptureContext cc, Block b)
532                 {
533                         CaptureContext = cc;
534                         ScopeBlock = b;
535                         id = count++;
536
537                         cc.AddScope (this);
538                 }
539
540                 public void AddLocal (LocalInfo li)
541                 {
542                         if (locals.Contains (li))
543                                 return;
544
545                         locals.Add (li);
546 }
547         
548                 public bool IsCaptured (LocalInfo li)
549                 {
550                         return locals.Contains (li);
551                 }
552                 
553                 internal void AddChild (ScopeInfo si)
554                 {
555                         if (children.Contains (si))
556                                 return;
557
558                         //
559                         // If any of the current children should be a children of `si', move them there
560                         //
561                         ArrayList move_queue = null;
562                         foreach (ScopeInfo child in children){
563                                 if (child.ScopeBlock.IsChildOf (si.ScopeBlock)){
564                                         if (move_queue == null)
565                                                 move_queue = new ArrayList ();
566                                         move_queue.Add (child);
567                                         child.ParentScope = si;
568                                         si.AddChild (child);
569                                 }
570                         }
571                         
572                         children.Add (si);
573
574                         if (move_queue != null){
575                                 foreach (ScopeInfo child in move_queue){
576                                         children.Remove (child);
577                                 }
578                         }
579                 } 
580
581                 static int indent = 0;
582
583                 void Pad ()
584                 {
585                         for (int i = 0; i < indent; i++)
586                                 Console.Write ("    ");
587                 }
588
589                 void EmitDebug ()
590                 {
591                         //Console.WriteLine (Environment.StackTrace);
592                         Pad ();
593                         Console.WriteLine ("START");
594                         indent++;
595                         Pad ();
596                         Console.WriteLine ("NeedThis=" + NeedThis);
597                         foreach (LocalInfo li in locals){
598                                 Pad ();
599                                 Console.WriteLine ("var {0}", li.Name);
600                         }
601                         
602                         foreach (ScopeInfo si in children)
603                                 si.EmitDebug ();
604                         indent--;
605                         Pad ();
606                         Console.WriteLine ("END");
607                 }
608                 
609                 public string MakeHelperName ()
610                 {
611                         return String.Format ("<>AnonHelp<{0}>", id);
612                 }
613
614                 public void EmitScopeType (EmitContext ec)
615                 {
616                         // EmitDebug ();
617
618                         if (ScopeTypeBuilder != null)
619                                 return;
620                         
621                         TypeBuilder container = ec.TypeContainer.TypeBuilder;
622
623                         CaptureContext.Host.CreateScopeType (ec, this);
624                         
625                         if (NeedThis)
626                                 THIS = ScopeTypeBuilder.DefineField ("<>THIS", container, FieldAttributes.Assembly);
627
628                         if (ParentScope != null){
629                                 if (ParentScope.ScopeTypeBuilder == null){
630                                         throw new Exception (String.Format ("My parent has not been initialized {0} and {1}", ParentScope, this));
631                                 }
632
633                                 if (ParentScope.ScopeTypeBuilder != ScopeTypeBuilder)
634                                         ParentLink = ScopeTypeBuilder.DefineField ("<>parent", ParentScope.ScopeTypeBuilder,
635                                                                                    FieldAttributes.Assembly);
636                         }
637                         
638                         if (NeedThis && ParentScope != null)
639                                 throw new Exception ("I was not expecting THIS && having a parent");
640
641                         foreach (LocalInfo info in locals)
642                                 info.FieldBuilder = ScopeTypeBuilder.DefineField (
643                                         info.Name, info.VariableType, FieldAttributes.Assembly);
644
645                         if (HostsParameters){
646                                 Hashtable captured_parameters = CaptureContext.captured_parameters;
647                                 
648                                 foreach (DictionaryEntry de in captured_parameters){
649                                         string name = (string) de.Key;
650                                         CapturedParameter cp = (CapturedParameter) de.Value;
651                                         FieldBuilder fb;
652                                         
653                                         fb = ScopeTypeBuilder.DefineField ("<p:" + name + ">", cp.Type, FieldAttributes.Assembly);
654                                         cp.FieldBuilder = fb;
655                                 }
656                         }
657
658                         foreach (ScopeInfo si in children){
659                                 si.EmitScopeType (ec);
660                         }
661                 }
662
663                 public void CloseTypes ()
664                 {
665                         RootContext.RegisterCompilerGeneratedType (ScopeTypeBuilder);
666                         foreach (ScopeInfo si in children)
667                                 si.CloseTypes ();
668                 }
669
670                 //
671                 // Emits the initialization code for the scope
672                 //
673                 public void EmitInitScope (EmitContext ec)
674                 {
675                         ILGenerator ig = ec.ig;
676
677                         if (inited)
678                                 return;
679
680                         if (ScopeConstructor == null)
681                                 throw new Exception ("ScopeConstructor is null for" + this.ToString ());
682                         
683                         if (!CaptureContext.Host.IsIterator) {
684                                 scope_instance = ig.DeclareLocal (ScopeTypeBuilder);
685                                 ig.Emit (OpCodes.Newobj, (ConstructorInfo) ScopeConstructor);
686                                 ig.Emit (OpCodes.Stloc, scope_instance);
687                         }
688
689                         if (THIS != null){
690                                 if (CaptureContext.Host.IsIterator) {
691                                         ig.Emit (OpCodes.Ldarg_0);
692                                         ig.Emit (OpCodes.Ldarg_1);
693                                 } else {
694                                         ig.Emit (OpCodes.Ldloc, scope_instance);
695                                         ig.Emit (OpCodes.Ldarg_0);
696                                 }
697                                 ig.Emit (OpCodes.Stfld, THIS);
698                         }
699
700                         //
701                         // Copy the parameter values, if any
702                         //
703                         int extra = ec.IsStatic ? 0 : 1;
704                         if (CaptureContext.Host.IsIterator)
705                                 extra++;
706                         if (HostsParameters){
707                                 Hashtable captured_parameters = CaptureContext.captured_parameters;
708                                 
709                                 foreach (DictionaryEntry de in captured_parameters){
710                                         CapturedParameter cp = (CapturedParameter) de.Value;
711
712                                         EmitScopeInstance (ig);
713                                         ParameterReference.EmitLdArg (ig, cp.Idx + extra);
714                                         ig.Emit (OpCodes.Stfld, cp.FieldBuilder);
715                                 }
716                         }
717
718                         if (ParentScope != null){
719                                 if (!ParentScope.inited)
720                                         ParentScope.EmitInitScope (ec);
721
722                                 if (ParentScope.ScopeTypeBuilder != ScopeTypeBuilder) {
723                                         //
724                                         // Only emit initialization in our capturecontext world
725                                         //
726                                         if (ParentScope.CaptureContext == CaptureContext){
727                                                 EmitScopeInstance (ig);
728                                                 ParentScope.EmitScopeInstance (ig);
729                                                 ig.Emit (OpCodes.Stfld, ParentLink);
730                                         } else {
731                                                 EmitScopeInstance (ig);
732                                                 ig.Emit (OpCodes.Ldarg_0);
733                                                 ig.Emit (OpCodes.Stfld, ParentLink);
734                                         }
735                                 }
736                         }
737                         inited = true;
738                 }
739
740                 public void EmitScopeInstance (ILGenerator ig)
741                 {
742                         if (CaptureContext.Host.IsIterator)
743                                 ig.Emit (OpCodes.Ldarg_0);
744                         else
745                                 ig.Emit (OpCodes.Ldloc, scope_instance);
746                 }
747
748                 static void DoPath (StringBuilder sb, ScopeInfo start)
749                 {
750                         if (start.ParentScope != null){
751                                 DoPath (sb, start.ParentScope);
752                                 sb.Append (", ");
753                         }
754                         sb.Append ((start.id).ToString ());
755                 }
756                 
757                 public override string ToString ()
758                 {
759                         StringBuilder sb = new StringBuilder ();
760                         
761                         sb.Append ("{");
762                         if (CaptureContext != null){
763                                 sb.Append (CaptureContext.ToString ());
764                                 sb.Append (":");
765                         }
766
767                         DoPath (sb, this);
768                         sb.Append ("}");
769
770                         return sb.ToString ();
771                 }
772         }
773
774         //
775         // CaptureContext objects are created on demand if a method has
776         // anonymous methods and kept on the ToplevelBlock.
777         //
778         // If they exist, all ToplevelBlocks in the containing block are
779         // linked together (children pointing to their parents).
780         //
781         public class CaptureContext {
782                 public static int count;
783                 public int cc_id;
784                 public Location loc;
785                 
786                 //
787                 // Points to the toplevel block that owns this CaptureContext
788                 //
789                 ToplevelBlock toplevel_owner;
790                 Hashtable scopes = new Hashtable ();
791                 bool have_captured_vars = false;
792                 bool referenced_this = false;
793                 ScopeInfo topmost = null;
794
795                 //
796                 // Captured fields
797                 //
798                 Hashtable captured_fields = new Hashtable ();
799                 Hashtable captured_variables = new Hashtable ();
800                 public Hashtable captured_parameters = new Hashtable ();
801                 public AnonymousContainer Host;
802                 
803                 public CaptureContext (ToplevelBlock toplevel_owner, Location loc,
804                                        AnonymousContainer host)
805                 {
806                         cc_id = count++;
807                         this.toplevel_owner = toplevel_owner;
808                         this.loc = loc;
809
810                         if (host != null)
811                                 Host = host;
812                 }
813
814                 void DoPath (StringBuilder sb, CaptureContext cc)
815                 {
816                         if (cc.ParentCaptureContext != null){
817                                 DoPath (sb, cc.ParentCaptureContext);
818                                 sb.Append (".");
819                         }
820                         sb.Append (cc.cc_id.ToString ());
821                 }
822
823                 public void ReParent (ToplevelBlock new_toplevel, AnonymousContainer new_host)
824                 {
825                         toplevel_owner = new_toplevel;
826                         Host = new_host;
827
828                         for (CaptureContext cc = ParentCaptureContext; cc != null;
829                              cc = cc.ParentCaptureContext) {
830                                 cc.Host = new_host;
831                         }
832                 }
833                 
834                 public override string ToString ()
835                 {
836                         StringBuilder sb = new StringBuilder ();
837                         sb.Append ("[");
838                         DoPath (sb, this);
839                         sb.Append ("]");
840                         return sb.ToString ();
841                 }
842
843                 public ToplevelBlock ParentToplevel {
844                         get {
845                                 return toplevel_owner.Container;
846                         }
847                 }
848
849                 public CaptureContext ParentCaptureContext {
850                         get {
851                                 ToplevelBlock parent = ParentToplevel;
852                                 
853                                 return (parent == null) ? null : parent.CaptureContext;
854                         }
855                 }
856
857                 // Returns the deepest of two scopes
858                 public ScopeInfo Deepest (ScopeInfo a, ScopeInfo b)
859                 {
860                         ScopeInfo p;
861
862                         if (a == null)
863                                 return b;
864                         if (b == null)
865                                 return a;
866                         if (a == b)
867                                 return a;
868
869                         //
870                         // If they Scopes are on the same CaptureContext, we do the double
871                         // checks just so if there is an invariant change in the future,
872                         // we get the exception at the end
873                         //
874                         for (p = a; p != null; p = p.ParentScope)
875                                 if (p == b)
876                                         return a;
877                         
878                         for (p = b; p != null; p = p.ParentScope)
879                                 if (p == a)
880                                         return b;
881
882                         CaptureContext ca = a.CaptureContext;
883                         CaptureContext cb = b.CaptureContext;
884
885                         for (CaptureContext c = ca; c != null; c = c.ParentCaptureContext)
886                                 if (c == cb)
887                                         return a;
888
889                         for (CaptureContext c = cb; c != null; c = c.ParentCaptureContext)
890                                 if (c == ca)
891                                         return b;
892                         throw new Exception ("Should never be reached");
893                 }
894
895                 void AdjustMethodScope (AnonymousContainer am, ScopeInfo scope)
896                 {
897                         am.Scope = Deepest (am.Scope, scope);
898                 }
899
900                 void LinkScope (ScopeInfo scope, int id)
901                 {
902                         ScopeInfo parent = (ScopeInfo) scopes [id];
903                         scope.ParentScope = parent;
904                         parent.AddChild (scope);
905
906                         if (scope == topmost)
907                                 topmost = parent;
908                 }
909                 
910                 public void AddLocal (AnonymousContainer am, LocalInfo li)
911                 {
912                         if (li.Block.Toplevel != toplevel_owner){
913                                 ParentCaptureContext.AddLocal (am, li);
914                                 return;
915                         }
916                         int block_id = li.Block.ID;
917                         ScopeInfo scope;
918                         if (scopes [block_id] == null){
919                                 scope = new ScopeInfo (this, li.Block);
920                                 scopes [block_id] = scope;
921                         } else
922                                 scope = (ScopeInfo) scopes [block_id];
923
924                         if (topmost == null){
925                                 topmost = scope;
926                         } else {
927                                 // Link to parent
928
929                                 for (Block b = scope.ScopeBlock.Parent; b != null; b = b.Parent){
930                                         if (scopes [b.ID] != null){
931                                                 LinkScope (scope, b.ID);
932                                                 break;
933                                         }
934                                 }
935
936                                 if (scope.ParentScope == null && ParentCaptureContext != null){
937                                         CaptureContext pcc = ParentCaptureContext;
938                                         
939                                         for (Block b = am.ContainingBlock; b != null; b = b.Parent){
940                                                 if (pcc.scopes [b.ID] != null){
941                                                         pcc.LinkScope (scope, b.ID);
942                                                         break;
943                                                 }
944                                         }
945                                 }
946                         }
947
948                         //
949                         // Adjust the owner
950                         //
951                         if (Host != null)
952                                 AdjustMethodScope (Host, topmost);
953
954                         //
955                         // Adjust the user
956                         //
957                         AdjustMethodScope (am, scope);
958                         
959                         if (captured_variables [li] != null)
960                                 return;
961                         
962                         have_captured_vars = true;
963                         captured_variables [li] = li;
964                         scope.AddLocal (li);
965                 }
966
967                 //
968                 // Retursn the CaptureContext for the block that defines the parameter `name'
969                 //
970                 static CaptureContext _ContextForParameter (ToplevelBlock current, string name)
971                 {
972                         ToplevelBlock container = current.Container;
973                         if (container != null){
974                                 CaptureContext cc = _ContextForParameter (container, name);
975                                 if (cc != null)
976                                         return cc;
977                         }
978                         if (current.IsParameterReference (name))
979                                 return current.ToplevelBlockCaptureContext;
980                         return null;
981                 }
982
983                 static CaptureContext ContextForParameter (ToplevelBlock current, string name)
984                 {
985                         CaptureContext cc = _ContextForParameter (current, name);
986                         if (cc == null)
987                                 throw new Exception (String.Format ("request for parameteter {0} failed: not found", name));
988                         return cc;
989                 }
990                 
991                 //
992                 // Records the captured parameter at the appropriate CaptureContext
993                 //
994                 public void AddParameter (EmitContext ec, AnonymousContainer am,
995                                           string name, Type t, int idx)
996                 {
997                         CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
998
999                         cc.AddParameterToContext (am, name, t, idx);
1000                 }
1001
1002                 //
1003                 // Records the parameters in the context
1004                 //
1005                 public void AddParameterToContext (AnonymousContainer am, string name, Type t, int idx)
1006                 {
1007                         if (captured_parameters == null)
1008                                 captured_parameters = new Hashtable ();
1009                         if (captured_parameters [name] != null)
1010                                 return;
1011                         captured_parameters [name] = new CapturedParameter (t, idx);
1012
1013                         if (topmost == null){
1014                                 //
1015                                 // Create one ScopeInfo, if there are none.
1016                                 //
1017                                 topmost = new ScopeInfo (this, toplevel_owner);
1018                                 scopes [toplevel_owner.ID] = topmost;
1019                         } else {
1020                                 //
1021                                 // If the topmost ScopeInfo is not at the topblock level, insert
1022                                 // a new ScopeInfo there.
1023                                 //
1024                                 // FIXME: This code probably should be evolved to be like the code
1025                                 // in AddLocal
1026                                 //
1027                                 if (topmost.ScopeBlock != toplevel_owner){
1028                                         ScopeInfo par_si = new ScopeInfo (this, toplevel_owner);
1029                                         ScopeInfo old_top = topmost;
1030                                         scopes [toplevel_owner.ID] = topmost;
1031                                         topmost.ParentScope = par_si;
1032                                         topmost = par_si;
1033                                         topmost.AddChild (old_top);
1034                                 }
1035                         }
1036                         
1037                         topmost.HostsParameters = true;
1038                         AdjustMethodScope (am, topmost);
1039                 }
1040
1041                 //
1042                 // Captured fields are only recorded on the topmost CaptureContext, because that
1043                 // one is the one linked to the owner of instance fields
1044                 //
1045                 public void AddField (FieldExpr fe)
1046                 {
1047                         if (fe.FieldInfo.IsStatic)
1048                                 throw new Exception ("Attempt to register a static field as a captured field");
1049                         
1050                         CaptureContext parent = ParentCaptureContext;
1051                         if (parent != null)
1052                                 parent.AddField (fe);
1053                         else
1054                                 captured_fields [fe] = fe;
1055                 }
1056
1057                 public void CaptureThis ()
1058                 {
1059                         CaptureContext parent = ParentCaptureContext;
1060                         if (parent != null)
1061                                 parent.CaptureThis ();
1062                         referenced_this = true;
1063                 }
1064
1065                 public bool HaveCapturedVariables {
1066                         get {
1067                                 return have_captured_vars;
1068                         }
1069                 }
1070                 
1071                 public bool HaveCapturedFields {
1072                         get {
1073                                 CaptureContext parent = ParentCaptureContext;
1074                                 if (parent != null)
1075                                         return parent.HaveCapturedFields;
1076                                 return captured_fields.Count > 0;
1077                         }
1078                 }
1079
1080                 public bool IsCaptured (LocalInfo local)
1081                 {
1082                         foreach (ScopeInfo si in scopes.Values){
1083                                 if (si.IsCaptured (local))
1084                                         return true;
1085                         }
1086                         return false;
1087                 }
1088
1089                 //
1090                 // Returns whether the parameter is captured
1091                 //
1092                 public bool IsParameterCaptured (string name)
1093                 {
1094                         if (ParentCaptureContext != null && ParentCaptureContext.IsParameterCaptured (name))
1095                                 return true;
1096                         
1097                         if (captured_parameters != null)
1098                                 return captured_parameters [name] != null;
1099                         return false;
1100                 }
1101
1102                 public void EmitAnonymousHelperClasses (EmitContext ec)
1103                 {
1104                         if (topmost != null){
1105                                 topmost.NeedThis = HaveCapturedFields || referenced_this;
1106                                 topmost.EmitScopeType (ec);
1107                         } 
1108                 }
1109
1110                 public void CloseAnonymousHelperClasses ()
1111                 {
1112                         if (topmost != null)
1113                                 topmost.CloseTypes ();
1114                 }
1115
1116                 public void EmitInitScope (EmitContext ec)
1117                 {
1118                         EmitAnonymousHelperClasses (ec);
1119                         if (topmost != null)
1120                                 topmost.EmitInitScope (ec);
1121                 }
1122
1123                 ScopeInfo GetScopeFromBlock (EmitContext ec, Block b)
1124                 {
1125                         ScopeInfo si;
1126                         
1127                         si = (ScopeInfo) scopes [b.ID];
1128                         if (si == null)
1129                                 throw new Exception ("Si is null for block " + b.ID);
1130                         si.EmitInitScope (ec);
1131
1132                         return si;
1133                 }
1134
1135                 //
1136                 // Emits the opcodes necessary to load the instance of the captured
1137                 // variable in `li'
1138                 //
1139                 public void EmitCapturedVariableInstance (EmitContext ec, LocalInfo li,
1140                                                           AnonymousContainer am)
1141                 {
1142                         ILGenerator ig = ec.ig;
1143                         ScopeInfo si;
1144
1145                         if (li.Block.Toplevel == toplevel_owner){
1146                                 si = GetScopeFromBlock (ec, li.Block);
1147                                 si.EmitScopeInstance (ig);
1148                                 return;
1149                         }
1150
1151                         si = am.Scope;
1152                         ig.Emit (OpCodes.Ldarg_0);
1153                         if (si != null){
1154                                 if (am.IsIterator && (si.ScopeBlock.Toplevel == li.Block.Toplevel)) {
1155                                         return;
1156                                 }
1157
1158                                 while (si.ScopeBlock.ID != li.Block.ID){
1159                                         if (si.ParentLink != null)
1160                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
1161                                         si = si.ParentScope;
1162                                         if (si == null) {
1163                                                 si = am.Scope;
1164                                                 Console.WriteLine ("Target: {0} {1}", li.Block.ID, li.Name);
1165                                                 while (si.ScopeBlock.ID != li.Block.ID){
1166                                                         Console.WriteLine ("Trying: {0}", si.ScopeBlock.ID);
1167                                                         si = si.ParentScope;
1168                                                 }
1169
1170                                                 throw new Exception (
1171                                                              String.Format ("Never found block {0} starting at {1} while looking up {2}",
1172                                                                             li.Block.ID, am.Scope.ScopeBlock.ID, li.Name));
1173                                         }
1174                                 }
1175                         }
1176                 }
1177
1178                 //
1179                 // Internal routine that loads the instance to reach parameter `name'
1180                 //
1181                 void EmitParameterInstance (EmitContext ec, string name)
1182                 {
1183                         CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
1184                         if (cc != this){
1185                                 cc.EmitParameterInstance (ec, name);
1186                                 return;
1187                         }
1188                         
1189                         CapturedParameter par_info = (CapturedParameter) captured_parameters [name];
1190                         if (par_info != null){
1191                                 // 
1192                                 // FIXME: implementing this.
1193                                 //
1194                         }
1195                         ILGenerator ig = ec.ig;
1196
1197                         ScopeInfo si;
1198
1199                         if (ec.CurrentBlock.Toplevel == toplevel_owner){
1200                                 si = GetScopeFromBlock (ec, toplevel_owner);
1201                                 si.EmitScopeInstance (ig);
1202                                 return;
1203                         }
1204
1205                         si = ec.CurrentAnonymousMethod.Scope;
1206                         ig.Emit (OpCodes.Ldarg_0);
1207                         if (si != null){
1208                                 while (si.ParentLink != null) {
1209                                         ig.Emit (OpCodes.Ldfld, si.ParentLink);
1210                                         si = si.ParentScope;
1211                                 } 
1212                         }
1213                 }
1214
1215                 //
1216                 // Emits the code necessary to load the parameter named `name' within
1217                 // an anonymous method.
1218                 //
1219                 public void EmitParameter (EmitContext ec, string name)
1220                 {
1221                         CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
1222                         if (cc != this){
1223                                 cc.EmitParameter (ec, name);
1224                                 return;
1225                         }
1226                         EmitParameterInstance (ec, name);
1227                         CapturedParameter par_info = (CapturedParameter) captured_parameters [name];
1228                         if (par_info != null){
1229                                 // 
1230                                 // FIXME: implementing this.
1231                                 //
1232                         }
1233                         ec.ig.Emit (OpCodes.Ldfld, par_info.FieldBuilder);
1234                 }
1235
1236                 //
1237                 // Implements the assignment of `source' to the paramenter named `name' within
1238                 // an anonymous method.
1239                 //
1240                 public void EmitAssignParameter (EmitContext ec, string name, Expression source, bool leave_copy, bool prepare_for_load)
1241                 {
1242                         CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
1243                         if (cc != this){
1244                                 cc.EmitAssignParameter (ec, name, source, leave_copy, prepare_for_load);
1245                                 return;
1246                         }
1247                         ILGenerator ig = ec.ig;
1248                         CapturedParameter par_info = (CapturedParameter) captured_parameters [name];
1249
1250                         EmitParameterInstance (ec, name);
1251                         source.Emit (ec);
1252                         if (leave_copy)
1253                                 ig.Emit (OpCodes.Dup);
1254                         ig.Emit (OpCodes.Stfld, par_info.FieldBuilder);
1255                 }
1256
1257                 //
1258                 // Emits the address for the parameter named `name' within
1259                 // an anonymous method.
1260                 //
1261                 public void EmitAddressOfParameter (EmitContext ec, string name)
1262                 {
1263                         CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
1264                         if (cc != this){
1265                                 cc.EmitAddressOfParameter (ec, name);
1266                                 return;
1267                         }
1268                         EmitParameterInstance (ec, name);
1269                         CapturedParameter par_info = (CapturedParameter) captured_parameters [name];
1270                         ec.ig.Emit (OpCodes.Ldflda, par_info.FieldBuilder);
1271                 }
1272
1273                 //
1274                 // The following methods are only invoked on the host for the
1275                 // anonymous method.
1276                 //
1277                 public void EmitMethodHostInstance (EmitContext target, AnonymousContainer am)
1278                 {
1279                         ILGenerator ig = target.ig;
1280                         ScopeInfo si = am.Scope;
1281
1282                         if (si == null){
1283                                 ig.Emit (OpCodes.Ldarg_0);
1284                                 return;
1285                         }
1286
1287                         si.EmitInitScope (target);
1288                         si.EmitScopeInstance (ig);
1289                 }
1290
1291                 ArrayList all_scopes = new ArrayList ();
1292                 
1293                 public void AddScope (ScopeInfo si)
1294                 {
1295                         all_scopes.Add (si);
1296                         toplevel_owner.RegisterCaptureContext (this);
1297                 }
1298
1299                 //
1300                 // Links any scopes that were not linked previously
1301                 //
1302                 public void AdjustScopes ()
1303                 {
1304                         foreach (ScopeInfo scope in all_scopes){
1305                                 if (scope.ParentScope != null)
1306                                         continue;
1307
1308                                 for (Block b = scope.ScopeBlock.Parent; b != null; b = b.Parent){
1309                                         if (scopes [b.ID] != null){
1310                                                 LinkScope (scope, b.ID);
1311                                                 break;
1312                                         }
1313                                 }
1314
1315                                 if (scope.ParentScope == null && ParentCaptureContext != null){
1316                                         CaptureContext pcc = ParentCaptureContext;
1317                                         
1318                                         for (Block b = Host.ContainingBlock; b != null; b = b.Parent){
1319                                                 if (pcc.scopes [b.ID] != null){
1320                                                         pcc.LinkScope (scope, b.ID);
1321                                                         break;
1322                                                 }
1323                                         }
1324                                 }
1325                         }
1326                 }
1327         }
1328 }