2006-01-13 John Luke <john.luke@gmail.com>
[mono.git] / mcs / gmcs / iterators.cs
1 //
2 // iterators.cs: Support for implementing iterators
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc.
8 //
9 // TODO:
10 //    Flow analysis for Yield.
11 //    Emit calls to base object constructor.
12 //
13 // Generics note:
14 //    Current should be defined to return T, and IEnumerator.Current returns object
15 //
16
17 using System;
18 using System.Collections;
19 using System.Reflection;
20 using System.Reflection.Emit;
21
22 namespace Mono.CSharp {
23
24         public interface IIteratorContainer {
25
26                 //
27                 // Invoked if a yield statement is found in the body
28                 //
29                 void SetYields ();
30         }
31         
32         public class Yield : Statement {
33                 Expression expr;
34                 ArrayList finally_blocks;
35
36                 public Yield (Expression expr, Location l)
37                 {
38                         this.expr = expr;
39                         loc = l;
40                 }
41
42                 public static bool CheckContext (EmitContext ec, Location loc)
43                 {
44                         if (ec.InFinally) {
45                                 Report.Error (1625, loc, "Cannot yield in the body of a " +
46                                               "finally clause");
47                                 return false;
48                         } 
49                         
50                         if (ec.InUnsafe) {
51                                 Report.Error (1629, loc, "Unsafe code may not appear in iterators");
52                                 return false;
53                         }
54                         if (ec.InCatch){
55                                 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
56                                 return false;
57                         }
58
59                         AnonymousContainer am = ec.CurrentAnonymousMethod;
60                         if ((am != null) && !am.IsIterator){
61                                 Report.Error (1621, loc, "The yield statement cannot be used inside anonymous method blocks");
62                                 return false;
63                         }
64
65                         if (ec.CurrentBranching.InTryWithCatch ()) {
66                                 Report.Error (1626, loc, "Cannot yield a value in the body of a " +
67                                         "try block with a catch clause");
68                                 return false;
69                         }
70                         return true;
71                 }
72                 
73                 public override bool Resolve (EmitContext ec)
74                 {
75                         expr = expr.Resolve (ec);
76                         if (expr == null)
77                                 return false;
78
79                         if (!CheckContext (ec, loc))
80                                 return false;
81
82                         Iterator iterator = ec.CurrentIterator;
83
84                         if (expr.Type != iterator.IteratorType){
85                                 expr = Convert.ImplicitConversionRequired (
86                                         ec, expr, iterator.IteratorType, loc);
87                                 if (expr == null)
88                                         return false;
89                         }
90
91                         ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
92                         return true;
93                 }
94
95                 protected override void DoEmit (EmitContext ec)
96                 {
97                         ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
98                 }
99         }
100
101         public class YieldBreak : Statement {
102
103                 public YieldBreak (Location l)
104                 {
105                         loc = l;
106                 }
107
108                 public override bool Resolve (EmitContext ec)
109                 {
110                         if (!Yield.CheckContext (ec, loc))
111                                 return false;
112
113                         ec.CurrentBranching.CurrentUsageVector.Goto ();
114                         return true;
115                 }
116
117                 protected override void DoEmit (EmitContext ec)
118                 {
119                         ec.CurrentIterator.EmitYieldBreak (ec.ig);
120                 }
121         }
122
123         public class Iterator : Class {
124                 protected ToplevelBlock original_block;
125                 protected ToplevelBlock block;
126
127                 Type original_iterator_type;
128                 TypeExpr iterator_type_expr;
129                 bool is_enumerable;
130                 public readonly bool IsStatic;
131
132                 //
133                 // The state as we generate the iterator
134                 //
135                 Label move_next_ok, move_next_error;
136                 ArrayList resume_points = new ArrayList ();
137                 int pc;
138                 
139                 //
140                 // Context from the original method
141                 //
142                 GenericMethod generic_method;
143                 TypeContainer container;
144                 TypeExpr current_type;
145                 Type this_type;
146                 Parameters parameters;
147                 Parameters original_parameters;
148                 IMethodData orig_method;
149
150                 MethodInfo dispose_method;
151                 MoveNextMethod move_next_method;
152                 Constructor ctor;
153                 CaptureContext cc;
154
155                 Expression enumerator_type;
156                 Expression enumerable_type;
157                 Expression generic_enumerator_type;
158                 Expression generic_enumerable_type;
159                 TypeArguments generic_args;
160
161                 protected enum State {
162                         Uninitialized   = -2,
163                         After,
164                         Running
165                 }
166
167                 static int proxy_count;
168
169                 public void EmitYieldBreak (ILGenerator ig)
170                 {
171                         ig.Emit (OpCodes.Ldarg_0);
172                         IntConstant.EmitInt (ig, (int) State.After);
173                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
174                         ig.Emit (OpCodes.Br, move_next_error);
175                 }
176
177                 public void EmitMoveNext (EmitContext ec)
178                 {
179                         ILGenerator ig = ec.ig;
180
181                         move_next_ok = ig.DefineLabel ();
182                         move_next_error = ig.DefineLabel ();
183
184                         LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
185
186                         ig.BeginExceptionBlock ();
187
188                         Label dispatcher = ig.DefineLabel ();
189                         ig.Emit (OpCodes.Br, dispatcher);
190
191                         ResumePoint entry_point = new ResumePoint (null);
192                         resume_points.Add (entry_point);
193                         entry_point.Define (ig);
194
195                         ec.EmitTopBlock (orig_method, original_block);
196
197                         EmitYieldBreak (ig);
198
199                         ig.MarkLabel (dispatcher);
200
201                         Label [] labels = new Label [resume_points.Count];
202                         for (int i = 0; i < labels.Length; i++)
203                                 labels [i] = ((ResumePoint) resume_points [i]).Label;
204
205                         ig.Emit (OpCodes.Ldarg_0);
206                         ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
207                         ig.Emit (OpCodes.Switch, labels);
208
209                         Label end = ig.DefineLabel ();
210
211                         ig.MarkLabel (move_next_error);
212                         ig.Emit (OpCodes.Ldc_I4_0); 
213                         ig.Emit (OpCodes.Stloc, retval);
214                         ig.Emit (OpCodes.Leave, end);
215
216                         ig.MarkLabel (move_next_ok);
217                         ig.Emit (OpCodes.Ldc_I4_1);
218                         ig.Emit (OpCodes.Stloc, retval);
219                         ig.Emit (OpCodes.Leave, end);
220
221                         ig.BeginFaultBlock ();
222
223                         ig.Emit (OpCodes.Ldarg_0);
224                         ig.Emit (OpCodes.Callvirt, dispose_method);
225
226                         ig.EndExceptionBlock ();
227
228                         ig.MarkLabel (end);
229                         ig.Emit (OpCodes.Ldloc, retval);
230                         ig.Emit (OpCodes.Ret);
231                 }
232
233                 public void EmitDispose (EmitContext ec)
234                 {
235                         ILGenerator ig = ec.ig;
236
237                         Label end = ig.DefineLabel ();
238                         Label dispatcher = ig.DefineLabel ();
239                         ig.Emit (OpCodes.Br, dispatcher);
240
241                         Label [] labels = new Label [resume_points.Count];
242                         for (int i = 0; i < labels.Length; i++) {
243                                 ResumePoint point = (ResumePoint) resume_points [i];
244
245                                 if (point.FinallyBlocks == null) {
246                                         labels [i] = end;
247                                         continue;
248                                 }
249
250                                 labels [i] = ig.DefineLabel ();
251                                 ig.MarkLabel (labels [i]);
252
253                                 ig.BeginExceptionBlock ();
254                                 ig.BeginFinallyBlock ();
255
256                                 foreach (ExceptionStatement stmt in point.FinallyBlocks) {
257                                         if (stmt != null)
258                                                 stmt.EmitFinally (ec);
259                                 }
260
261                                 ig.EndExceptionBlock ();
262                                 ig.Emit (OpCodes.Br, end);
263                         }
264
265                         ig.MarkLabel (dispatcher);
266                         ig.Emit (OpCodes.Ldarg_0);
267                         ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
268                         ig.Emit (OpCodes.Switch, labels);
269
270                         ig.Emit (OpCodes.Ldarg_0);
271                         IntConstant.EmitInt (ig, (int) State.After);
272                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
273
274                         ig.MarkLabel (end);
275                 }
276
277                 protected class ResumePoint
278                 {
279                         public Label Label;
280                         public readonly ExceptionStatement[] FinallyBlocks;
281
282                         public ResumePoint (ArrayList list)
283                         {
284                                 if (list != null) {
285                                         FinallyBlocks = new ExceptionStatement [list.Count];
286                                         list.CopyTo (FinallyBlocks, 0);
287                                 }
288                         }
289
290                         public void Define (ILGenerator ig)
291                         {
292                                 Label = ig.DefineLabel ();
293                                 ig.MarkLabel (Label);
294                         }
295                 }
296
297                 //
298                 // Called back from Yield
299                 //
300                 public void MarkYield (EmitContext ec, Expression expr,
301                                        ArrayList finally_blocks)
302                 {
303                         ILGenerator ig = ec.ig;
304
305                         // Store the new current
306                         ig.Emit (OpCodes.Ldarg_0);
307                         expr.Emit (ec);
308                         ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
309
310                         // increment pc
311                         pc++;
312                         ig.Emit (OpCodes.Ldarg_0);
313                         IntConstant.EmitInt (ig, pc);
314                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
315
316                         // Return ok
317                         ig.Emit (OpCodes.Br, move_next_ok);
318
319                         ResumePoint point = new ResumePoint (finally_blocks);
320                         resume_points.Add (point);
321                         point.Define (ig);
322                 }
323
324                 public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
325                 {
326                         ILGenerator ig = ec.ig;
327
328                         // increment pc
329                         pc++;
330                         ig.Emit (OpCodes.Ldarg_0);
331                         IntConstant.EmitInt (ig, pc);
332                         ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
333
334                         ResumePoint point = new ResumePoint (finally_blocks);
335                         resume_points.Add (point);
336                         point.Define (ig);
337                 }
338
339                 private static MemberName MakeProxyName (string name, GenericMethod generic, Location loc)
340                 {
341                         int pos = name.LastIndexOf ('.');
342                         if (pos > 0)
343                                 name = name.Substring (pos + 1);
344
345                         string proxy_name = "<" + name + ">__" + (proxy_count++);
346
347                         if (generic != null) {
348                                 TypeArguments args = new TypeArguments (loc);
349                                 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
350                                         args.Add (new SimpleName (tparam.Name, loc));
351                                 return new MemberName (proxy_name, args, loc);
352                         } else
353                                 return new MemberName (proxy_name, loc);
354                 }
355
356                 //
357                 // Our constructor
358                 //
359                 public Iterator (IMethodData m_container, TypeContainer container, GenericMethod generic,
360                                  int modifiers)
361                         : base (container.NamespaceEntry, container,
362                                 MakeProxyName (m_container.MethodName.Name, generic, m_container.Location),
363                                 (modifiers & Modifiers.UNSAFE) | Modifiers.PRIVATE, null)
364                 {
365                         this.orig_method = m_container;
366
367                         this.generic_method = generic;
368                         this.container = container;
369                         this.original_parameters = m_container.ParameterInfo;
370                         this.original_block = orig_method.Block;
371                         this.block = new ToplevelBlock (orig_method.Block, parameters, orig_method.Location);
372
373                         if (generic != null) {
374                                 ArrayList constraints = new ArrayList ();
375                                 foreach (TypeParameter tparam in generic.TypeParameters)
376                                         constraints.Add (tparam.Constraints);
377
378                                 SetParameterInfo (constraints);
379                         }
380
381                         IsStatic = (modifiers & Modifiers.STATIC) != 0;
382                 }
383
384                 public AnonymousContainer Host {
385                         get { return move_next_method; }
386                 }
387
388                 public bool DefineIterator ()
389                 {
390                         ec = new EmitContext (this, Location, null, null, ModFlags);
391                         ec.CurrentAnonymousMethod = move_next_method;
392                         ec.InIterator = true;
393
394                         if (!CheckType ()) {
395                                 Report.Error (1624, Location,
396                                         "The body of `{0}' cannot be an iterator block because `{1}' is not an iterator interface type",
397                                         orig_method.GetSignatureForError (), TypeManager.CSharpName (orig_method.ReturnType));
398                                 return false;
399                         }
400
401                         for (int i = 0; i < original_parameters.Count; i++){
402                                 Parameter.Modifier mod = original_parameters.ParameterModifier (i);
403                                 if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
404                                         Report.Error (
405                                                 1623, Location,
406                                                 "Iterators cannot have ref or out parameters");
407                                         return false;
408                                 }
409
410                                 if ((mod & Parameter.Modifier.ARGLIST) != 0) {
411                                         Report.Error (1636, Location, "__arglist is not allowed in parameter list of iterators");
412                                         return false;
413                                 }
414
415                                 if (original_parameters.ParameterType (i).IsPointer) {
416                                         Report.Error (1637, Location, "Iterators cannot have unsafe parameters or yield types");
417                                         return false;
418                                 }
419                         }
420
421                         if (container.CurrentType != null)
422                                 this_type = container.CurrentType;
423                         else
424                                 this_type = container.TypeBuilder;
425
426                         container.AddIterator (this);
427
428                         orig_method.Block = block;
429                         return true;
430                 }
431
432                 MethodInfo FetchMethodDispose ()
433                 {
434                         MemberList dispose_list;
435
436                         dispose_list = FindMembers (
437                                 current_type.Type,
438                                 MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance,
439                                 Type.FilterName, "Dispose");
440
441                         if (dispose_list.Count != 1)
442                                 throw new InternalErrorException ("Cannot find Dipose() method.");
443
444                         return (MethodInfo) dispose_list [0];
445                 }
446
447                 protected override bool DoDefineMembers ()
448                 {
449                         ec.InIterator = true;
450                         ec.CurrentAnonymousMethod = move_next_method;
451                         ec.capture_context = cc;
452
453                         if (!base.DoDefineMembers ())
454                                 return false;
455
456                         dispose_method = FetchMethodDispose ();
457                         if (dispose_method == null)
458                                 return false;
459
460                         return true;
461                 }
462
463                 public override bool Define ()
464                 {
465                         if (!base.Define ())
466                                 return false;
467
468                         ec.InIterator = true;
469                         ec.CurrentAnonymousMethod = move_next_method;
470                         ec.capture_context = cc;
471
472                         ec.TypeContainer = ec.TypeContainer.Parent;
473
474                         if (ec.TypeContainer.CurrentType != null)
475                                 ec.ContainerType = ec.TypeContainer.CurrentType;
476                         else
477                                 ec.ContainerType = ec.TypeContainer.TypeBuilder;
478
479                         ec.ig = move_next_method.method.MethodBuilder.GetILGenerator ();
480
481                         if (!ctor.Define ())
482                                 return false;
483
484                         bool unreachable;
485
486                         if (!ec.ResolveTopBlock (null, original_block, parameters, orig_method, out unreachable))
487                                 return false;
488
489                         if (!ec.ResolveTopBlock (null, block, parameters, orig_method, out unreachable))
490                                 return false;
491
492                         original_block.CompleteContexts ();
493
494                         cc.EmitAnonymousHelperClasses (ec);
495
496                         return true;
497                 }
498
499                 TypeExpr InflateType (Type it)
500                 {
501                         if (generic_method == null)
502                                 return new TypeExpression (it, Location);
503
504                         if (it.IsGenericParameter && (it.DeclaringMethod != null)) {
505                                 int pos = it.GenericParameterPosition;
506                                 it = CurrentTypeParameters [pos].Type;
507                         } else if (it.IsGenericInstance) {
508                                 Type[] args = it.GetGenericArguments ();
509
510                                 TypeArguments inflated = new TypeArguments (Location);
511                                 foreach (Type t in args)
512                                         inflated.Add (InflateType (t));
513
514                                 return new ConstructedType (it, inflated, Location);
515                         } else if (it.IsArray) {
516                                 TypeExpr et_expr = InflateType (it.GetElementType ());
517                                 int rank = it.GetArrayRank ();
518
519                                 Type et = et_expr.ResolveAsTypeTerminal (ec).Type;
520                                 it = et.MakeArrayType (rank);
521                         }
522
523                         return new TypeExpression (it, Location);
524                 }
525
526                 Parameter InflateParameter (Parameter param)
527                 {
528                         TypeExpr te = InflateType (param.ParameterType);
529                         return new Parameter (
530                                 te, param.Name, param.ModFlags, param.OptAttributes, param.Location);
531                 }
532
533                 Parameters InflateParameters (Parameters parameters, EmitContext ec)
534                 {
535                         int count = parameters.FixedParameters.Length;
536                         if (count == 0)
537                                 return Parameters.EmptyReadOnlyParameters;
538                         Parameter[] fixed_params = new Parameter [count];
539                         for (int i = 0; i < count; i++)
540                                 fixed_params [i] = InflateParameter (parameters.FixedParameters [i]);
541
542                         return new Parameters (fixed_params, parameters.HasArglist);
543                 }
544
545                 protected override TypeExpr [] GetClassBases (out TypeExpr base_class)
546                 {
547                         iterator_type_expr = InflateType (original_iterator_type);
548
549                         generic_args = new TypeArguments (Location);
550                         generic_args.Add (iterator_type_expr);
551
552                         ArrayList list = new ArrayList ();
553                         if (is_enumerable) {
554                                 enumerable_type = new TypeExpression (
555                                         TypeManager.ienumerable_type, Location);
556                                 list.Add (enumerable_type);
557
558                                 generic_enumerable_type = new ConstructedType (
559                                         TypeManager.generic_ienumerable_type,
560                                         generic_args, Location);
561                                 list.Add (generic_enumerable_type);
562                         }
563
564                         enumerator_type = new TypeExpression (
565                                 TypeManager.ienumerator_type, Location);
566                         list.Add (enumerator_type);
567
568                         list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
569
570                         generic_enumerator_type = new ConstructedType (
571                                 TypeManager.generic_ienumerator_type,
572                                 generic_args, Location);
573                         list.Add (generic_enumerator_type);
574
575                         Bases = list;
576
577                         return base.GetClassBases (out base_class);
578                 }
579
580                 //
581                 // Returns the new block for the method, or null on failure
582                 //
583                 protected override bool DefineNestedTypes ()
584                 {
585                         if (CurrentType != null)
586                                 current_type = new TypeExpression (CurrentType, Location);
587                         else
588                                 current_type = new TypeExpression (TypeBuilder, Location);
589
590                         if (IsGeneric) {
591                                 foreach (TypeParameter tparam in TypeParameters)
592                                         tparam.InflateConstraints (current_type.Type);
593                         }
594
595                         parameters = InflateParameters (original_parameters, ec);
596                         if (!parameters.Resolve (ec)) {
597                                 // TODO:
598                         }
599
600                         Define_Fields ();
601                         Define_Current (false);
602                         Define_Current (true);
603                         Define_MoveNext ();
604                         Define_Reset ();
605                         Define_Dispose ();
606
607                         Define_Constructor ();
608
609                         Create_Block ();
610
611                         if (is_enumerable) {
612                                 Define_GetEnumerator (false);
613                                 Define_GetEnumerator (true);
614                         }
615
616                         return base.DefineNestedTypes ();
617                 }
618
619                 Field pc_field;
620                 Field current_field;
621                 Method dispose;
622
623                 void Create_Block ()
624                 {
625                         original_block.SetHaveAnonymousMethods (Location, move_next_method);
626                         block.SetHaveAnonymousMethods (Location, move_next_method);
627
628                         cc = original_block.CaptureContext;
629
630                         int first = IsStatic ? 0 : 1;
631
632                         ArrayList args = new ArrayList ();
633                         if (!IsStatic) {
634                                 Type t = this_type;
635                                 args.Add (new Argument (
636                                         new ThisParameterReference (t, Location)));
637                                 cc.CaptureThis (move_next_method);
638                         }
639
640                         args.Add (new Argument (new BoolLiteral (false, Location)));
641
642                         for (int i = 0; i < parameters.Count; i++) {
643                                 Type t = original_parameters.ParameterType (i);
644                                 Type inflated = parameters.ParameterType (i);
645                                 string name = parameters.ParameterName (i);
646
647                                 args.Add (new Argument (
648                                         new SimpleParameterReference (t, first + i, Location)));
649
650                                 cc.AddParameterToContext (move_next_method, name, inflated, first + i);
651                         }
652
653                         TypeExpr proxy_type;
654                         if (generic_method != null) {
655                                 TypeArguments new_args = new TypeArguments (Location);
656                                 if (Parent.IsGeneric) {
657                                         foreach (TypeParameter tparam in Parent.TypeParameters)
658                                                 new_args.Add (new TypeParameterExpr (tparam, Location));
659                                 }
660                                 foreach (TypeParameter tparam in generic_method.TypeParameters)
661                                         new_args.Add (new TypeParameterExpr (tparam, Location));
662                                 ConstructedType ct = new ConstructedType (CurrentType, new_args, Location);
663                                 proxy_type = ct.ResolveAsTypeTerminal (ec);
664                         } else
665                                 proxy_type = current_type;
666
667                         Expression new_expr = new New (proxy_type, args, Location);
668                         block.AddStatement (new NoCheckReturn (new_expr, Location));
669                 }
670
671                 void Define_Fields ()
672                 {
673                         pc_field = new Field (
674                                 this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "$PC",
675                                 null, Location);
676                         AddField (pc_field);
677
678                         current_field = new Field (
679                                 this, iterator_type_expr, Modifiers.PRIVATE, "$current",
680                                 null, Location);
681                         AddField (current_field);
682                 }
683
684                 void Define_Constructor ()
685                 {
686                         Parameters ctor_params;
687
688                         ArrayList list = new ArrayList ();
689
690                         if (!IsStatic)
691                                 list.Add (new Parameter (
692                                         new TypeExpression (this_type, Location),
693                                         "this", Parameter.Modifier.NONE,
694                                         null, Location));
695                         list.Add (new Parameter (
696                                 TypeManager.bool_type, "initialized",
697                                 Parameter.Modifier.NONE, null, Location));
698
699                         Parameter[] old_fixed = parameters.FixedParameters;
700                         list.AddRange (old_fixed);
701
702                         Parameter[] fixed_params = new Parameter [list.Count];
703                         list.CopyTo (fixed_params);
704
705                         ctor_params = new Parameters (fixed_params);
706
707                         ctor = new Constructor (
708                                 this, MemberName.Name, Modifiers.PUBLIC, ctor_params,
709                                 new GeneratedBaseInitializer (Location),
710                                 Location);
711                         AddConstructor (ctor);
712
713                         ctor.Block = new ToplevelBlock (block, parameters, Location);
714
715                         int first = IsStatic ? 2 : 3;
716
717                         State initial = is_enumerable ? State.Uninitialized : State.Running;
718                         ctor.Block.AddStatement (new SetState (this, initial, Location));
719
720                         ctor.Block.AddStatement (new If (
721                                 new SimpleParameterReference (
722                                         TypeManager.bool_type, first - 1, Location),
723                                 new SetState (this, State.Running, Location),
724                                 Location));
725
726                         ctor.Block.AddStatement (new InitScope (this, Location));
727                 }
728
729                 Statement Create_ThrowInvalidOperation ()
730                 {
731                         TypeExpr ex_type = new TypeExpression (
732                                 TypeManager.invalid_operation_exception_type, Location);
733
734                         return new Throw (new New (ex_type, null, Location), Location);
735                 }
736
737                 Statement Create_ThrowNotSupported ()
738                 {
739                         TypeExpr ex_type = new TypeExpression (
740                                 TypeManager.not_supported_exception_type, Location);
741
742                         return new Throw (new New (ex_type, null, Location), Location);
743                 }
744
745                 void Define_Current (bool is_generic)
746                 {
747                         MemberName left;
748                         Expression type;
749                         if (is_generic) {
750                                 left = new MemberName (
751                                         "System.Collections.Generic.IEnumerator",
752                                         generic_args, Location);
753                                 type = iterator_type_expr;
754                         } else {
755                                 left = new MemberName ("System.Collections.IEnumerator", Location);
756                                 type = TypeManager.system_object_expr;
757                         }
758
759                         MemberName name = new MemberName (left, "Current", null, Location);
760
761                         ToplevelBlock get_block = new ToplevelBlock (
762                                 block, parameters, Location);
763
764                         get_block.AddStatement (new If (
765                                 new Binary (
766                                         Binary.Operator.LessThanOrEqual,
767                                         new FieldExpression (this, pc_field),
768                                         new IntLiteral ((int) State.Running, pc_field.Location)),
769                                 Create_ThrowInvalidOperation (),
770                                 new Return (
771                                         new FieldExpression (this, current_field), Location),
772                                 Location));
773
774                         Accessor getter = new Accessor (get_block, 0, null, Location);
775
776                         Property current = new Property (
777                                 this, type, 0, false, name, null, getter, null);
778                         AddProperty (current);
779                 }
780
781                 void Define_MoveNext ()
782                 {
783                         move_next_method = new MoveNextMethod (this, Location);
784
785                         original_block.ReParent (block, move_next_method);
786
787                         move_next_method.CreateMethod (ec);
788
789                         AddMethod (move_next_method.method);
790                 }
791
792                 void Define_GetEnumerator (bool is_generic)
793                 {
794                         MemberName left;
795                         Expression type;
796                         if (is_generic) {
797                                 left = new MemberName (
798                                         "System.Collections.Generic.IEnumerable",
799                                         generic_args, Location);
800                                 type = generic_enumerator_type;
801                         } else {
802                                 left = new MemberName ("System.Collections.IEnumerable", Location);
803                                 type = enumerator_type;
804                         }
805
806                         MemberName name = new MemberName (left, "GetEnumerator", Location);
807
808                         Method get_enumerator = new Method (
809                                 this, null, type, 0, false, name,
810                                 Parameters.EmptyReadOnlyParameters, null);
811                         AddMethod (get_enumerator);
812
813                         get_enumerator.Block = new ToplevelBlock (
814                                 block, parameters, Location);
815
816                         get_enumerator.Block.SetHaveAnonymousMethods (Location, move_next_method);
817
818                         Expression ce = new MemberAccess (
819                                 new SimpleName ("System.Threading.Interlocked", Location),
820                                 "CompareExchange", Location);
821
822                         Expression pc = new FieldExpression (this, pc_field);
823                         Expression before = new IntLiteral ((int) State.Running, Location);
824                         Expression uninitialized = new IntLiteral ((int) State.Uninitialized, Location);
825
826                         ArrayList args = new ArrayList ();
827                         args.Add (new Argument (pc, Argument.AType.Ref));
828                         args.Add (new Argument (before, Argument.AType.Expression));
829                         args.Add (new Argument (uninitialized, Argument.AType.Expression));
830
831                         get_enumerator.Block.AddStatement (new If (
832                                 new Binary (
833                                         Binary.Operator.Equality,
834                                         new Invocation (ce, args),
835                                         uninitialized),
836                                 new Return (new ThisParameterReference (type.Type, Location),
837                                             Location),
838                                 Location));
839
840                         args = new ArrayList ();
841                         if (!IsStatic) {
842                                 args.Add (new Argument (new CapturedThisReference (this, Location)));
843                         }
844
845                         args.Add (new Argument (new BoolLiteral (true, Location)));
846
847                         for (int i = 0; i < parameters.Count; i++) {
848                                 Expression cp = new CapturedParameterReference (
849                                         this, parameters.ParameterType (i),
850                                         parameters.ParameterName (i), Location);
851                                 args.Add (new Argument (cp));
852                         }
853
854                         Expression new_expr = new New (current_type, args, Location);
855                         get_enumerator.Block.AddStatement (new Return (new_expr, Location));
856                 }
857
858                 protected class SimpleParameterReference : Expression
859                 {
860                         int idx;
861
862                         public SimpleParameterReference (Type type, int idx, Location loc)
863                         {
864                                 this.idx = idx;
865                                 this.loc = loc;
866                                 this.type = type;
867                                 eclass = ExprClass.Variable;
868                         }
869
870                         public override Expression DoResolve (EmitContext ec)
871                         {
872                                 return this;
873                         }
874
875                         public override void Emit (EmitContext ec)
876                         {
877                                 DoEmit (ec);
878                         }
879
880                         protected virtual void DoEmit (EmitContext ec)
881                         {
882                                 ParameterReference.EmitLdArg (ec.ig, idx);
883                         }
884                 }
885
886                 protected class ThisParameterReference : SimpleParameterReference, IMemoryLocation
887                 {
888                         public ThisParameterReference (Type type, Location loc)
889                                 : base (type, 0, loc)
890                         { }
891
892                         protected override void DoEmit (EmitContext ec)
893                         {
894                                 base.DoEmit (ec);
895                                 if (ec.TypeContainer is Struct)
896                                         ec.ig.Emit (OpCodes.Ldobj, type);
897                         }
898
899                         public void AddressOf (EmitContext ec, AddressOp mode)
900                         {
901                                 if (ec.TypeContainer is Struct)
902                                         ec.ig.Emit (OpCodes.Ldarga, 0);
903                                 else
904                                         ec.ig.Emit (OpCodes.Ldarg, 0);
905                         }
906                 }
907
908                 protected class CapturedParameterReference : Expression
909                 {
910                         Iterator iterator;
911                         string name;
912
913                         public CapturedParameterReference (Iterator iterator, Type type,
914                                                            string name, Location loc)
915                         {
916                                 this.iterator = iterator;
917                                 this.loc = loc;
918                                 this.type = type;
919                                 this.name = name;
920                                 eclass = ExprClass.Variable;
921                         }
922
923                         public override Expression DoResolve (EmitContext ec)
924                         {
925                                 return this;
926                         }
927
928                         public override void Emit (EmitContext ec)
929                         {
930                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
931
932                                 LocalTemporary dummy = null;
933                                 
934                                 iterator.cc.EmitParameter (ec, name, false, false, ref dummy);
935                         }
936                 }
937
938                 protected class CapturedThisReference : Expression
939                 {
940                         public CapturedThisReference (Iterator iterator, Location loc)
941                         {
942                                 this.loc = loc;
943                                 this.type = iterator.this_type;
944                                 eclass = ExprClass.Variable;
945                         }
946
947                         public override Expression DoResolve (EmitContext ec)
948                         {
949                                 return this;
950                         }
951
952                         public override void Emit (EmitContext ec)
953                         {
954                                 ec.EmitThis (false);
955                         }
956                 }
957
958                 protected class FieldExpression : Expression
959                 {
960                         Iterator iterator;
961                         Field field;
962
963                         public FieldExpression (Iterator iterator, Field field)
964                         {
965                                 this.iterator = iterator;
966                                 this.field = field;
967                                 this.loc = iterator.Location;
968                         }
969
970                         public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
971                         {
972                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
973                                 fexpr.InstanceExpression = new ThisParameterReference (
974                                         iterator.this_type, loc);
975                                 return fexpr.ResolveLValue (ec, right_side, loc);
976                         }
977
978                         public override Expression DoResolve (EmitContext ec)
979                         {
980                                 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
981                                 fexpr.InstanceExpression = new ThisParameterReference (
982                                         iterator.this_type, loc);
983                                 return fexpr.Resolve (ec);
984                         }
985
986                         public override void Emit (EmitContext ec)
987                         {
988                                 throw new InvalidOperationException ();
989                         }
990                 }
991
992                 protected class MoveNextMethod : AnonymousContainer
993                 {
994                         Iterator iterator;
995
996                         public MoveNextMethod (Iterator iterator, Location loc)
997                                 : base (iterator.parameters, iterator.original_block, loc)
998                         {
999                                 this.iterator = iterator;
1000                         }
1001
1002                         protected override bool CreateMethodHost (EmitContext ec)
1003                         {
1004                                 method = new Method (
1005                                         iterator, null, TypeManager.system_boolean_expr,
1006                                         Modifiers.PUBLIC, false, new MemberName ("MoveNext", loc),
1007                                         Parameters.EmptyReadOnlyParameters, null);
1008
1009                                 method.Block = Block;
1010
1011                                 MoveNextStatement inline = new MoveNextStatement (iterator, loc);
1012                                 Block.AddStatement (inline);
1013
1014                                 return true;
1015                         }
1016
1017                         public bool CreateMethod (EmitContext ec)
1018                         {
1019                                 return CreateMethodHost (ec);
1020                         }
1021
1022                         public override Iterator Iterator {
1023                                 get { return iterator; }
1024                         }
1025
1026                         public override bool IsIterator {
1027                                 get { return true; }
1028                         }
1029
1030                         public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
1031                         {
1032                                 scope.ScopeTypeBuilder = iterator.TypeBuilder;
1033                                 scope.ScopeConstructor = iterator.ctor.ConstructorBuilder;
1034                         }
1035
1036                         public override void Emit (EmitContext ec)
1037                         {
1038                                 throw new InternalErrorException ();
1039                         }
1040                 }
1041
1042                 protected class MoveNextStatement : Statement {
1043                         Iterator iterator;
1044
1045                         public MoveNextStatement (Iterator iterator, Location loc)
1046                         {
1047                                 this.loc = loc;
1048                                 this.iterator = iterator;
1049                         }
1050
1051                         public override bool Resolve (EmitContext ec)
1052                         {
1053                                 return true;
1054                         }
1055
1056                         protected override void DoEmit (EmitContext ec)
1057                         {
1058                                 ec.CurrentAnonymousMethod = iterator.move_next_method;
1059                                 ec.InIterator = true;
1060
1061                                 iterator.EmitMoveNext (ec);
1062                         }
1063                 }
1064
1065                 protected class DisposeMethod : Statement {
1066                         Iterator iterator;
1067
1068                         public DisposeMethod (Iterator iterator, Location loc)
1069                         {
1070                                 this.loc = loc;
1071                                 this.iterator = iterator;
1072                         }
1073
1074                         public override bool Resolve (EmitContext ec)
1075                         {
1076                                 return true;
1077                         }
1078
1079                         protected override void DoEmit (EmitContext ec)
1080                         {
1081                                 iterator.EmitDispose (ec);
1082                         }
1083                 }
1084
1085                 protected class StatementList : Statement {
1086                         ArrayList statements;
1087
1088                         public StatementList (Location loc)
1089                         {
1090                                 this.loc = loc;
1091                                 statements = new ArrayList ();
1092                         }
1093
1094                         public void Add (Statement statement)
1095                         {
1096                                 statements.Add (statement);
1097                         }
1098
1099                         public override bool Resolve (EmitContext ec)
1100                         {
1101                                 foreach (Statement stmt in statements) {
1102                                         if (!stmt.Resolve (ec))
1103                                                 return false;
1104                                 }
1105
1106                                 return true;
1107                         }
1108
1109                         protected override void DoEmit (EmitContext ec)
1110                         {
1111                                 foreach (Statement stmt in statements)
1112                                         stmt.Emit (ec);
1113                         }
1114                 }
1115
1116                 protected class SetState : Statement
1117                 {
1118                         Iterator iterator;
1119                         State state;
1120
1121                         public SetState (Iterator iterator, State state, Location loc)
1122                         {
1123                                 this.iterator = iterator;
1124                                 this.state = state;
1125                                 this.loc = loc;
1126                         }
1127
1128                         public override bool Resolve (EmitContext ec)
1129                         {
1130                                 return true;
1131                         }
1132
1133                         protected override void DoEmit (EmitContext ec)
1134                         {
1135                                 ec.ig.Emit (OpCodes.Ldarg_0);
1136                                 IntConstant.EmitInt (ec.ig, (int) state);
1137                                 ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
1138                         }
1139                 }
1140
1141                 protected class InitScope : Statement
1142                 {
1143                         Iterator iterator;
1144
1145                         public InitScope (Iterator iterator, Location loc)
1146                         {
1147                                 this.iterator = iterator;
1148                                 this.loc = loc;
1149                         }
1150
1151                         public override bool Resolve (EmitContext ec)
1152                         {
1153                                 return true;
1154                         }
1155
1156                         protected override void DoEmit (EmitContext ec)
1157                         {
1158                                 iterator.cc.EmitInitScope (ec);
1159                         }
1160                 }
1161
1162                 void Define_Reset ()
1163                 {
1164                         Method reset = new Method (
1165                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1166                                 false, new MemberName ("Reset", Location),
1167                                 Parameters.EmptyReadOnlyParameters, null);
1168                         AddMethod (reset);
1169
1170                         reset.Block = new ToplevelBlock (Location);
1171                         reset.Block = new ToplevelBlock (block, parameters, Location);
1172                         reset.Block.SetHaveAnonymousMethods (Location, move_next_method);
1173
1174                         reset.Block.AddStatement (Create_ThrowNotSupported ());
1175                 }
1176
1177                 void Define_Dispose ()
1178                 {
1179                         dispose = new Method (
1180                                 this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
1181                                 false, new MemberName ("Dispose", Location),
1182                                 Parameters.EmptyReadOnlyParameters, null);
1183                         AddMethod (dispose);
1184
1185                         dispose.Block = new ToplevelBlock (block, parameters, Location);
1186                         dispose.Block.SetHaveAnonymousMethods (Location, move_next_method);
1187
1188                         dispose.Block.AddStatement (new DisposeMethod (this, Location));
1189                 }
1190
1191                 public Type IteratorType {
1192                         get { return iterator_type_expr.Type; }
1193                 }
1194
1195                 //
1196                 // This return statement tricks return into not flagging an error for being
1197                 // used in a Yields method
1198                 //
1199                 class NoCheckReturn : Statement {
1200                         public Expression Expr;
1201                 
1202                         public NoCheckReturn (Expression expr, Location l)
1203                         {
1204                                 Expr = expr;
1205                                 loc = l;
1206                         }
1207
1208                         public override bool Resolve (EmitContext ec)
1209                         {
1210                                 Expr = Expr.Resolve (ec);
1211                                 if (Expr == null)
1212                                         return false;
1213
1214                                 ec.CurrentBranching.CurrentUsageVector.Return ();
1215
1216                                 return true;
1217                         }
1218
1219                         protected override void DoEmit (EmitContext ec)
1220                         {
1221                                 Expr.Emit (ec);
1222                                 ec.ig.Emit (OpCodes.Ret);
1223                         }
1224                 }
1225
1226                 bool CheckType ()
1227                 {
1228                         Type ret = orig_method.ReturnType;
1229
1230                         if (ret == TypeManager.ienumerable_type) {
1231                                 original_iterator_type = TypeManager.object_type;
1232                                 is_enumerable = true;
1233                                 return true;
1234                         }
1235                         if (ret == TypeManager.ienumerator_type) {
1236                                 original_iterator_type = TypeManager.object_type;
1237                                 is_enumerable = false;
1238                                 return true;
1239                         }
1240
1241                         if (!ret.IsGenericInstance)
1242                                 return false;
1243
1244                         Type[] args = TypeManager.GetTypeArguments (ret);
1245                         if (args.Length != 1)
1246                                 return false;
1247
1248                         Type gt = ret.GetGenericTypeDefinition ();
1249                         if (gt == TypeManager.generic_ienumerable_type) {
1250                                 original_iterator_type = args [0];
1251                                 is_enumerable = true;
1252                                 return true;
1253                         } else if (gt == TypeManager.generic_ienumerator_type) {
1254                                 original_iterator_type = args [0];
1255                                 is_enumerable = false;
1256                                 return true;
1257                         }
1258
1259                         return false;
1260                 }
1261         }
1262 }
1263