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