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