2 // iterators.cs: Support for implementing iterators
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2003 Ximian, Inc.
10 // Flow analysis for Yield.
11 // Emit calls to base object constructor.
14 // Current should be defined to return T, and IEnumerator.Current returns object
18 using System.Collections;
19 using System.Reflection;
20 using System.Reflection.Emit;
22 namespace Mono.CSharp {
24 public interface IIteratorContainer {
27 // Invoked if a yield statement is found in the body
32 public class Yield : Statement {
33 public Expression expr;
34 ArrayList finally_blocks;
36 public Yield (Expression expr, Location l)
42 public static bool CheckContext (EmitContext ec, Location loc)
44 if (ec.CurrentBranching.InFinally (true)){
45 Report.Error (1625, loc, "Cannot yield in the body of a " +
50 Report.Error (1629, loc, "Unsafe code may not appear in iterators");
53 if (ec.CurrentBranching.InCatch ()){
54 Report.Error (1631, loc, "Cannot yield in the body of a " +
58 if (ec.CurrentAnonymousMethod != null){
59 Report.Error (1621, loc, "yield statement can not appear inside an anonymoud method");
64 // FIXME: Missing check for Yield inside try block that contains catch clauses
69 public override bool Resolve (EmitContext ec)
71 expr = expr.Resolve (ec);
74 if (!CheckContext (ec, loc))
77 Iterator iterator = ec.CurrentIterator;
78 if (expr.Type != iterator.IteratorType){
79 expr = Convert.ImplicitConversionRequired (
80 ec, expr, iterator.IteratorType, loc);
85 ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
89 protected override void DoEmit (EmitContext ec)
91 ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
95 public class YieldBreak : Statement {
97 public YieldBreak (Location l)
102 public override bool Resolve (EmitContext ec)
104 if (!Yield.CheckContext (ec, loc))
107 ec.CurrentBranching.CurrentUsageVector.Goto ();
111 protected override void DoEmit (EmitContext ec)
113 ec.CurrentIterator.EmitYieldBreak (ec.ig);
117 public class Iterator : Class {
118 ToplevelBlock original_block;
120 string original_name;
123 TypeExpr iterator_type_expr;
130 // The state as we generate the iterator
132 Label move_next_ok, move_next_error;
133 ArrayList resume_points = new ArrayList ();
137 // Context from the original method
139 TypeContainer container;
141 InternalParameters parameters;
143 protected enum State {
149 static int proxy_count;
151 public void EmitYieldBreak (ILGenerator ig)
153 ig.Emit (OpCodes.Ldarg_0);
154 IntConstant.EmitInt (ig, (int) State.After);
155 ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
156 ig.Emit (OpCodes.Br, move_next_error);
159 public void EmitMoveNext (EmitContext ec)
161 ILGenerator ig = ec.ig;
163 move_next_ok = ig.DefineLabel ();
164 move_next_error = ig.DefineLabel ();
166 LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
168 ig.BeginExceptionBlock ();
170 Label dispatcher = ig.DefineLabel ();
171 ig.Emit (OpCodes.Br, dispatcher);
173 ResumePoint entry_point = new ResumePoint (null);
174 resume_points.Add (entry_point);
175 entry_point.Define (ig);
177 ec.EmitTopBlock (original_block, parameters, Location);
180 ig.MarkLabel (dispatcher);
182 Label [] labels = new Label [resume_points.Count];
183 for (int i = 0; i < labels.Length; i++)
184 labels [i] = ((ResumePoint) resume_points [i]).Label;
186 ig.Emit (OpCodes.Ldarg_0);
187 ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
188 ig.Emit (OpCodes.Switch, labels);
190 Label end = ig.DefineLabel ();
192 ig.MarkLabel (move_next_error);
193 ig.Emit (OpCodes.Ldc_I4_0);
194 ig.Emit (OpCodes.Stloc, retval);
195 ig.Emit (OpCodes.Leave, end);
197 ig.MarkLabel (move_next_ok);
198 ig.Emit (OpCodes.Ldc_I4_1);
199 ig.Emit (OpCodes.Stloc, retval);
200 ig.Emit (OpCodes.Leave, end);
202 ig.BeginFaultBlock ();
204 ig.Emit (OpCodes.Ldarg_0);
205 ig.Emit (OpCodes.Callvirt, dispose.MethodBuilder);
207 ig.EndExceptionBlock ();
210 ig.Emit (OpCodes.Ldloc, retval);
211 ig.Emit (OpCodes.Ret);
214 public void EmitDispose (EmitContext ec)
216 ILGenerator ig = ec.ig;
218 Label end = ig.DefineLabel ();
219 Label dispatcher = ig.DefineLabel ();
220 ig.Emit (OpCodes.Br, dispatcher);
222 ec.RemapToProxy = true;
223 Label [] labels = new Label [resume_points.Count];
224 for (int i = 0; i < labels.Length; i++) {
225 ResumePoint point = (ResumePoint) resume_points [i];
227 if (point.FinallyBlocks == null) {
232 labels [i] = ig.DefineLabel ();
233 ig.MarkLabel (labels [i]);
235 ig.BeginExceptionBlock ();
236 ig.BeginFinallyBlock ();
238 foreach (ExceptionStatement stmt in point.FinallyBlocks) {
240 stmt.EmitFinally (ec);
243 ig.EndExceptionBlock ();
244 ig.Emit (OpCodes.Br, end);
246 ec.RemapToProxy = false;
248 ig.MarkLabel (dispatcher);
249 ig.Emit (OpCodes.Ldarg_0);
250 ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
251 ig.Emit (OpCodes.Switch, labels);
253 ig.Emit (OpCodes.Ldarg_0);
254 IntConstant.EmitInt (ig, (int) State.After);
255 ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
260 protected class ResumePoint
263 public readonly ExceptionStatement[] FinallyBlocks;
265 public ResumePoint (ArrayList list)
268 FinallyBlocks = new ExceptionStatement [list.Count];
269 list.CopyTo (FinallyBlocks, 0);
273 public void Define (ILGenerator ig)
275 Label = ig.DefineLabel ();
276 ig.MarkLabel (Label);
281 // Invoked when a local variable declaration needs to be mapped to
282 // a field in our proxy class
284 // Prefixes registered:
285 // v_ for EmitContext.MapVariable
288 public FieldBuilder MapVariable (string pfx, string name, Type t)
290 string full_name = pfx + name;
291 FieldBuilder fb = (FieldBuilder) fields [full_name];
295 fb = TypeBuilder.DefineField (full_name, t, FieldAttributes.Private);
296 fields.Add (full_name, fb);
301 // Called back from Yield
303 public void MarkYield (EmitContext ec, Expression expr,
304 ArrayList finally_blocks)
306 ILGenerator ig = ec.ig;
308 // Store the new current
309 ig.Emit (OpCodes.Ldarg_0);
311 ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
315 ig.Emit (OpCodes.Ldarg_0);
316 IntConstant.EmitInt (ig, pc);
317 ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
320 ig.Emit (OpCodes.Br, move_next_ok);
322 ResumePoint point = new ResumePoint (finally_blocks);
323 resume_points.Add (point);
327 public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
329 ILGenerator ig = ec.ig;
333 ig.Emit (OpCodes.Ldarg_0);
334 IntConstant.EmitInt (ig, pc);
335 ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
337 ResumePoint point = new ResumePoint (finally_blocks);
338 resume_points.Add (point);
342 private static MemberName MakeProxyName (string name)
344 int pos = name.LastIndexOf ('.');
346 name = name.Substring (pos + 1);
348 return new MemberName ("<" + name + ">__" + (proxy_count++));
354 public Iterator (TypeContainer container, string name, Type return_type,
355 InternalParameters parameters,
356 int modifiers, ToplevelBlock block, Location loc)
357 : base (container.NamespaceEntry, container, MakeProxyName (name),
358 (modifiers & Modifiers.UNSAFE) | Modifiers.PRIVATE, null, loc)
360 this.container = container;
361 this.return_type = return_type;
362 this.parameters = parameters;
363 this.original_name = name;
364 this.original_block = block;
365 this.block = new ToplevelBlock (loc);
367 fields = new Hashtable ();
369 is_static = (modifiers & Modifiers.STATIC) != 0;
372 public bool DefineIterator ()
374 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
376 if (!CheckType (return_type)) {
379 "The body of `{0}' cannot be an iterator block " +
380 "because '{1}' is not an iterator interface type",
381 original_name, TypeManager.CSharpName (return_type));
385 for (int i = 0; i < parameters.Count; i++){
386 Parameter.Modifier mod = parameters.ParameterModifier (i);
387 if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
390 "Iterators cannot have ref or out parameters");
395 ArrayList list = new ArrayList ();
397 list.Add (new TypeExpression (
398 TypeManager.ienumerable_type, Location));
399 list.Add (new TypeExpression (TypeManager.ienumerator_type, Location));
400 list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
402 iterator_type_expr = new TypeExpression (iterator_type, Location);
404 container.AddIterator (this);
411 // Returns the new block for the method, or null on failure
413 protected override bool DefineNestedTypes ()
416 Define_Constructor ();
423 Define_GetEnumerator ();
427 return base.DefineNestedTypes ();
435 public Field this_field;
436 public Field[] parameter_fields;
440 int first = is_static ? 0 : 1;
442 ArrayList args = new ArrayList ();
444 Type t = container.TypeBuilder;
445 args.Add (new Argument (
446 new ThisParameterReference (t, 0, Location)));
449 args.Add (new Argument (new BoolLiteral (false)));
451 for (int i = 0; i < parameters.Count; i++) {
452 Type t = parameters.ParameterType (i);
453 args.Add (new Argument (
454 new SimpleParameterReference (t, first + i, Location)));
457 Expression new_expr = new New (
458 new TypeExpression (TypeBuilder, Location), args, Location);
460 block.AddStatement (new NoCheckReturn (new_expr, Location));
463 void Define_Fields ()
465 Location loc = Location.Null;
467 pc_field = new Field (
468 this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "PC",
472 current_field = new Field (
473 this, iterator_type_expr, Modifiers.PRIVATE, "current",
475 AddField (current_field);
478 this_field = new Field (
480 new TypeExpression (container.TypeBuilder, Location),
481 Modifiers.PRIVATE, "this", null, null, loc);
482 AddField (this_field);
485 parameter_fields = new Field [parameters.Count];
486 for (int i = 0; i < parameters.Count; i++) {
487 string fname = String.Format (
488 "field{0}_{1}", i, parameters.ParameterName (i));
490 parameter_fields [i] = new Field (
492 new TypeExpression (parameters.ParameterType (i), loc),
493 Modifiers.PRIVATE, fname, null, null, loc);
494 AddField (parameter_fields [i]);
498 void Define_Constructor ()
500 Parameters ctor_params;
502 ArrayList list = new ArrayList ();
505 list.Add (new Parameter (
506 new TypeExpression (container.TypeBuilder, Location),
507 "this", Parameter.Modifier.NONE, null));
508 list.Add (new Parameter (
509 TypeManager.system_boolean_expr, "initialized",
510 Parameter.Modifier.NONE, null));
512 Parameter[] old_fixed = parameters.Parameters.FixedParameters;
513 if (old_fixed != null)
514 list.AddRange (old_fixed);
516 Parameter[] fixed_params = new Parameter [list.Count];
517 list.CopyTo (fixed_params);
519 ctor_params = new Parameters (
520 fixed_params, parameters.Parameters.ArrayParameter,
523 Constructor ctor = new Constructor (
524 this, Name, Modifiers.PUBLIC, ctor_params,
525 new ConstructorBaseInitializer (
526 null, Parameters.EmptyReadOnlyParameters, Location),
528 AddConstructor (ctor);
530 ToplevelBlock block = ctor.Block = new ToplevelBlock (Location);
533 Type t = container.TypeBuilder;
535 Assign assign = new Assign (
536 new FieldExpression (this_field),
537 new SimpleParameterReference (t, 1, Location),
540 block.AddStatement (new StatementExpression (assign, Location));
543 int first = is_static ? 2 : 3;
545 for (int i = 0; i < parameters.Count; i++) {
546 Type t = parameters.ParameterType (i);
548 Assign assign = new Assign (
549 new FieldExpression (parameter_fields [i]),
550 new SimpleParameterReference (t, first + i, Location),
553 block.AddStatement (new StatementExpression (assign, Location));
556 State initial = is_enumerable ? State.Uninitialized : State.Running;
557 block.AddStatement (new SetState (this, initial, Location));
559 block.AddStatement (new If (
560 new SimpleParameterReference (
561 TypeManager.bool_type, first - 1, Location),
562 new SetState (this, State.Running, Location),
566 Statement Create_ThrowInvalidOperation ()
568 TypeExpr ex_type = new TypeExpression (
569 TypeManager.invalid_operation_exception_type, Location);
571 return new Throw (new New (ex_type, null, Location), Location);
574 Statement Create_ThrowNotSupported ()
576 TypeExpr ex_type = new TypeExpression (
577 TypeManager.not_supported_exception_type, Location);
579 return new Throw (new New (ex_type, null, Location), Location);
582 void Define_Current ()
584 ToplevelBlock get_block = new ToplevelBlock (Location);
585 MemberName left = new MemberName ("System.Collections.IEnumerator");
586 MemberName name = new MemberName (left, "Current");
588 get_block.AddStatement (new If (
590 Binary.Operator.LessThanOrEqual,
591 new FieldExpression (pc_field),
592 new IntLiteral ((int) State.Running), Location),
593 Create_ThrowInvalidOperation (),
595 new FieldExpression (current_field), Location),
598 Accessor getter = new Accessor (get_block, 0, null, Location);
600 Property current = new Property (
601 this, iterator_type_expr, 0,
602 false, name, null, getter, null, Location);
603 AddProperty (current);
606 void Define_MoveNext ()
608 Method move_next = new Method (
609 this, TypeManager.system_boolean_expr,
610 Modifiers.PUBLIC, false, new MemberName ("MoveNext"),
611 Parameters.EmptyReadOnlyParameters, null,
613 AddMethod (move_next);
615 ToplevelBlock block = move_next.Block = new ToplevelBlock (Location);
617 MoveNextMethod inline = new MoveNextMethod (this, Location);
618 block.AddStatement (inline);
621 void Define_GetEnumerator ()
623 MemberName left = new MemberName ("System.Collections.IEnumerable");
624 MemberName name = new MemberName (left, "GetEnumerator");
626 Method get_enumerator = new Method (
628 new TypeExpression (TypeManager.ienumerator_type, Location),
630 Parameters.EmptyReadOnlyParameters, null,
632 AddMethod (get_enumerator);
634 get_enumerator.Block = new ToplevelBlock (Location);
636 Expression ce = new MemberAccess (
637 new SimpleName ("System.Threading.Interlocked", Location),
638 "CompareExchange", Location);
640 Expression pc = new FieldExpression (pc_field);
641 Expression before = new IntLiteral ((int) State.Running);
642 Expression uninitialized = new IntLiteral ((int) State.Uninitialized);
644 ArrayList args = new ArrayList ();
645 args.Add (new Argument (pc, Argument.AType.Ref));
646 args.Add (new Argument (before, Argument.AType.Expression));
647 args.Add (new Argument (uninitialized, Argument.AType.Expression));
649 get_enumerator.Block.AddStatement (new If (
651 Binary.Operator.Equality,
652 new Invocation (ce, args, Location),
653 uninitialized, Location),
654 new Return (new This (block, Location), Location),
657 args = new ArrayList ();
659 args.Add (new Argument (new FieldExpression (this_field)));
661 args.Add (new Argument (new BoolLiteral (true)));
663 for (int i = 0; i < parameters.Count; i++)
664 args.Add (new Argument (
665 new FieldExpression (parameter_fields [i])));
667 Expression new_expr = new New (
668 new TypeExpression (TypeBuilder, Location), args, Location);
669 get_enumerator.Block.AddStatement (new Return (new_expr, Location));
672 protected class SimpleParameterReference : Expression
676 public SimpleParameterReference (Type type, int idx, Location loc)
681 eclass = ExprClass.Variable;
684 public override Expression DoResolve (EmitContext ec)
689 public override void Emit (EmitContext ec)
694 protected virtual void DoEmit (EmitContext ec)
696 ParameterReference.EmitLdArg (ec.ig, idx);
700 protected class ThisParameterReference : SimpleParameterReference
702 public ThisParameterReference (Type type, int idx, Location loc)
703 : base (type, idx, loc)
706 protected override void DoEmit (EmitContext ec)
709 if (ec.TypeContainer is Struct)
710 ec.ig.Emit (OpCodes.Ldobj, type);
714 protected class FieldExpression : Expression
718 public FieldExpression (Field field)
723 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
725 return DoResolve (ec);
728 public override Expression DoResolve (EmitContext ec)
730 FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
731 fexpr.InstanceExpression = ec.GetThis (loc);
732 return fexpr.Resolve (ec);
735 public override void Emit (EmitContext ec)
737 throw new InvalidOperationException ();
741 protected class MoveNextMethod : Statement {
744 public MoveNextMethod (Iterator iterator, Location loc)
747 this.iterator = iterator;
750 public override bool Resolve (EmitContext ec)
752 ec.CurrentBranching.CurrentUsageVector.Return ();
756 protected override void DoEmit (EmitContext ec)
758 int code_flags = Modifiers.METHOD_YIELDS;
759 if (iterator.is_static)
760 code_flags |= Modifiers.STATIC;
762 code_flags |= iterator.ModFlags & Modifiers.UNSAFE;
764 EmitContext new_ec = new EmitContext (
765 iterator.container, loc, ec.ig,
766 TypeManager.int32_type, code_flags);
768 new_ec.CurrentIterator = iterator;
770 iterator.EmitMoveNext (new_ec);
774 protected class DisposeMethod : Statement {
777 public DisposeMethod (Iterator iterator, Location loc)
780 this.iterator = iterator;
783 public override bool Resolve (EmitContext ec)
788 protected override void DoEmit (EmitContext ec)
790 iterator.EmitDispose (ec);
794 protected class StatementList : Statement {
795 ArrayList statements;
797 public StatementList (Location loc)
800 statements = new ArrayList ();
803 public void Add (Statement statement)
805 statements.Add (statement);
808 public override bool Resolve (EmitContext ec)
810 foreach (Statement stmt in statements) {
811 if (!stmt.Resolve (ec))
818 protected override void DoEmit (EmitContext ec)
820 foreach (Statement stmt in statements)
825 protected class SetState : Statement
830 public SetState (Iterator iterator, State state, Location loc)
832 this.iterator = iterator;
837 public override bool Resolve (EmitContext ec)
842 protected override void DoEmit (EmitContext ec)
844 ec.ig.Emit (OpCodes.Ldarg_0);
845 IntConstant.EmitInt (ec.ig, (int) state);
846 ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
852 Method reset = new Method (
853 this, TypeManager.system_void_expr, Modifiers.PUBLIC,
854 false, new MemberName ("Reset"),
855 Parameters.EmptyReadOnlyParameters, null, Location);
858 reset.Block = new ToplevelBlock (Location);
859 reset.Block.AddStatement (Create_ThrowNotSupported ());
862 void Define_Dispose ()
864 dispose = new Method (
865 this, TypeManager.system_void_expr, Modifiers.PUBLIC,
866 false, new MemberName ("Dispose"),
867 Parameters.EmptyReadOnlyParameters, null, Location);
870 dispose.Block = new ToplevelBlock (Location);
871 dispose.Block.AddStatement (new DisposeMethod (this, Location));
874 public ToplevelBlock Block {
875 get { return block; }
878 public Type IteratorType {
879 get { return iterator_type; }
883 // This return statement tricks return into not flagging an error for being
884 // used in a Yields method
886 class NoCheckReturn : Return {
887 public NoCheckReturn (Expression expr, Location loc) : base (expr, loc)
891 public override bool Resolve (EmitContext ec)
893 ec.InIterator = false;
894 bool ret_val = base.Resolve (ec);
895 ec.InIterator = true;
901 bool CheckType (Type t)
903 if (t == TypeManager.ienumerable_type) {
904 iterator_type = TypeManager.object_type;
905 is_enumerable = true;
907 } else if (t == TypeManager.ienumerator_type) {
908 iterator_type = TypeManager.object_type;
909 is_enumerable = false;