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