2009-02-19 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / iterators.cs
blob9f7b42c55bc41d08d386327cd5a0da9e740830b1
1 //
2 // iterators.cs: Support for implementing iterators
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003 Ximian, Inc.
10 // Copyright 2003-2008 Novell, Inc.
13 // TODO:
14 // Flow analysis for Yield.
17 using System;
18 using System.Collections;
19 using System.Reflection;
20 using System.Reflection.Emit;
22 namespace Mono.CSharp {
24 public class Yield : ResumableStatement {
25 Expression expr;
26 bool unwind_protect;
28 int resume_pc;
30 public Yield (Expression expr, Location l)
32 this.expr = expr;
33 loc = l;
36 public static bool CheckContext (EmitContext ec, Location loc)
38 for (Block block = ec.CurrentBlock; block != null; block = block.Parent) {
39 if (!block.Unsafe)
40 continue;
42 Report.Error (1629, loc, "Unsafe code may not appear in iterators");
43 return false;
47 // We can't use `ec.InUnsafe' here because it's allowed to have an iterator
48 // inside an unsafe class. See test-martin-29.cs for an example.
50 if (!ec.CurrentAnonymousMethod.IsIterator) {
51 Report.Error (1621, loc,
52 "The yield statement cannot be used inside " +
53 "anonymous method blocks");
54 return false;
57 return true;
60 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
62 expr.MutateHoistedGenericType (storey);
65 public override bool Resolve (EmitContext ec)
67 expr = expr.Resolve (ec);
68 if (expr == null)
69 return false;
71 Report.Debug (64, "RESOLVE YIELD #1", this, ec, expr, expr.GetType (),
72 ec.CurrentAnonymousMethod, ec.CurrentIterator);
74 if (!CheckContext (ec, loc))
75 return false;
77 Iterator iterator = ec.CurrentIterator;
78 if (expr.Type != iterator.OriginalIteratorType) {
79 expr = Convert.ImplicitConversionRequired (
80 ec, expr, iterator.OriginalIteratorType, loc);
81 if (expr == null)
82 return false;
85 if (!ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
86 unwind_protect = ec.CurrentBranching.AddResumePoint (this, loc, out resume_pc);
88 return true;
91 protected override void DoEmit (EmitContext ec)
93 ec.CurrentIterator.MarkYield (ec, expr, resume_pc, unwind_protect, resume_point);
96 protected override void CloneTo (CloneContext clonectx, Statement t)
98 Yield target = (Yield) t;
100 target.expr = expr.Clone (clonectx);
104 public class YieldBreak : ExitStatement {
105 public YieldBreak (Location l)
107 loc = l;
110 public override void Error_FinallyClause ()
112 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
115 protected override void CloneTo (CloneContext clonectx, Statement target)
117 throw new NotSupportedException ();
120 protected override bool DoResolve (EmitContext ec)
122 return Yield.CheckContext (ec, loc);
125 protected override void DoEmit (EmitContext ec)
127 ec.CurrentIterator.EmitYieldBreak (ec.ig, unwind_protect);
130 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
132 // nothing to do
137 // Wraps method block into iterator wrapper block
139 class IteratorStatement : Statement
141 Iterator iterator;
142 Block original_block;
144 public IteratorStatement (Iterator iterator, Block original_block)
146 this.iterator = iterator;
147 this.original_block = original_block;
148 this.loc = iterator.Location;
151 protected override void CloneTo (CloneContext clonectx, Statement target)
153 IteratorStatement t = (IteratorStatement) target;
154 t.original_block = (ExplicitBlock) original_block.Clone (clonectx);
155 t.iterator = (Iterator) iterator.Clone (clonectx);
158 public override bool Resolve (EmitContext ec)
160 ec.StartFlowBranching (iterator);
161 bool ok = original_block.Resolve (ec);
162 ec.EndFlowBranching ();
163 return ok;
166 protected override void DoEmit (EmitContext ec)
168 iterator.EmitMoveNext (ec, original_block);
171 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
173 original_block.MutateHoistedGenericType (storey);
174 iterator.MutateHoistedGenericType (storey);
178 public class IteratorStorey : AnonymousMethodStorey
180 class IteratorMethod : Method
182 readonly IteratorStorey host;
184 public IteratorMethod (IteratorStorey host, FullNamedExpression returnType, int mod, MemberName name)
185 : base (host, null, returnType, mod | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
186 name, ParametersCompiled.EmptyReadOnlyParameters, null)
188 this.host = host;
190 Block = new ToplevelBlock (host.Iterator.Container.Toplevel, ParametersCompiled.EmptyReadOnlyParameters, Location);
193 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
195 EmitContext ec = new EmitContext (
196 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
198 ec.CurrentAnonymousMethod = host.Iterator;
199 return ec;
203 class GetEnumeratorMethod : IteratorMethod
205 sealed class GetEnumeratorStatement : Statement
207 IteratorStorey host;
208 IteratorMethod host_method;
210 Expression new_storey;
212 public GetEnumeratorStatement (IteratorStorey host, IteratorMethod host_method)
214 this.host = host;
215 this.host_method = host_method;
216 loc = host_method.Location;
219 protected override void CloneTo (CloneContext clonectx, Statement target)
221 throw new NotSupportedException ();
224 public override bool Resolve (EmitContext ec)
226 TypeExpression storey_type_expr = new TypeExpression (host.TypeBuilder, loc);
227 ArrayList init = null;
228 if (host.hoisted_this != null) {
229 init = new ArrayList (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
230 HoistedThis ht = host.hoisted_this;
231 FieldExpr from = new FieldExpr (ht.Field.FieldBuilder, loc);
232 from.InstanceExpression = CompilerGeneratedThis.Instance;
233 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
236 if (host.hoisted_params != null) {
237 if (init == null)
238 init = new ArrayList (host.HoistedParameters.Count);
240 for (int i = 0; i < host.hoisted_params.Count; ++i) {
241 HoistedParameter hp = (HoistedParameter) host.hoisted_params [i];
242 HoistedParameter hp_cp = (HoistedParameter) host.hoisted_params_copy [i];
244 FieldExpr from = new FieldExpr (hp_cp.Field.FieldBuilder, loc);
245 from.InstanceExpression = CompilerGeneratedThis.Instance;
247 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
251 if (init != null) {
252 new_storey = new NewInitialize (storey_type_expr, new ArrayList (0),
253 new CollectionOrObjectInitializers (init, loc), loc);
254 } else {
255 new_storey = new New (storey_type_expr, new ArrayList (0), loc);
258 new_storey = new_storey.Resolve (ec);
259 if (new_storey != null)
260 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
262 if (TypeManager.int_interlocked_compare_exchange == null) {
263 Type t = TypeManager.CoreLookupType ("System.Threading", "Interlocked", Kind.Class, true);
264 if (t != null) {
265 TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
266 t, "CompareExchange", loc, TypeManager.int32_type,
267 TypeManager.int32_type, TypeManager.int32_type);
271 ec.CurrentBranching.CurrentUsageVector.Goto ();
272 return true;
275 protected override void DoEmit (EmitContext ec)
277 ILGenerator ig = ec.ig;
278 Label label_init = ig.DefineLabel ();
280 ig.Emit (OpCodes.Ldarg_0);
281 ig.Emit (OpCodes.Ldflda, host.PC.FieldBuilder);
282 IntConstant.EmitInt (ig, (int) Iterator.State.Start);
283 IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
284 ig.Emit (OpCodes.Call, TypeManager.int_interlocked_compare_exchange);
286 IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
287 ig.Emit (OpCodes.Bne_Un_S, label_init);
289 ig.Emit (OpCodes.Ldarg_0);
290 ig.Emit (OpCodes.Ret);
292 ig.MarkLabel (label_init);
294 new_storey.Emit (ec);
295 ig.Emit (OpCodes.Ret);
298 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
300 throw new NotSupportedException ();
304 public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
305 : base (host, returnType, 0, name)
307 Block.AddStatement (new GetEnumeratorStatement (host, this));
311 class DisposeMethod : IteratorMethod
313 sealed class DisposeMethodStatement : Statement
315 Iterator iterator;
317 public DisposeMethodStatement (Iterator iterator)
319 this.iterator = iterator;
320 this.loc = iterator.Location;
323 protected override void CloneTo (CloneContext clonectx, Statement target)
325 throw new NotSupportedException ();
328 public override bool Resolve (EmitContext ec)
330 return true;
333 protected override void DoEmit (EmitContext ec)
335 iterator.EmitDispose (ec);
338 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
340 throw new NotSupportedException ();
344 public DisposeMethod (IteratorStorey host)
345 : base (host, TypeManager.system_void_expr, Modifiers.PUBLIC, new MemberName ("Dispose", host.Location))
347 host.AddMethod (this);
349 Block = new ToplevelBlock (host.Iterator.Container, ParametersCompiled.EmptyReadOnlyParameters, Location);
350 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
355 // Uses Method as method info
357 class DynamicMethodGroupExpr : MethodGroupExpr
359 readonly Method method;
361 public DynamicMethodGroupExpr (Method method, Location loc)
362 : base (null, loc)
364 this.method = method;
367 public override Expression DoResolve (EmitContext ec)
369 Methods = new MethodBase [] { method.MethodBuilder };
370 type = method.Parent.TypeBuilder;
371 InstanceExpression = new CompilerGeneratedThis (type, Location);
372 return base.DoResolve (ec);
376 class DynamicFieldExpr : FieldExpr
378 readonly Field field;
380 public DynamicFieldExpr (Field field, Location loc)
381 : base (loc)
383 this.field = field;
386 public override Expression DoResolve (EmitContext ec)
388 FieldInfo = field.FieldBuilder;
389 type = TypeManager.TypeToCoreType (FieldInfo.FieldType);
390 InstanceExpression = new CompilerGeneratedThis (type, Location);
391 return base.DoResolve (ec);
395 public readonly Iterator Iterator;
397 TypeExpr iterator_type_expr;
398 Field pc_field;
399 Field current_field;
401 TypeExpr enumerator_type;
402 TypeExpr enumerable_type;
403 #if GMCS_SOURCE
404 TypeArguments generic_args;
405 TypeExpr generic_enumerator_type;
406 TypeExpr generic_enumerable_type;
407 #else
408 const TypeArguments generic_args = null;
409 #endif
411 ArrayList hoisted_params_copy;
412 int local_name_idx;
414 public IteratorStorey (Iterator iterator)
415 : base (iterator.Container.Toplevel, iterator.Host,
416 iterator.OriginalMethod as MemberBase, iterator.GenericMethod, "Iterator")
418 this.Iterator = iterator;
421 public Field PC {
422 get { return pc_field; }
425 public Field CurrentField {
426 get { return current_field; }
429 public ArrayList HoistedParameters {
430 get { return hoisted_params; }
433 protected override TypeExpr [] ResolveBaseTypes (out TypeExpr base_class)
435 iterator_type_expr = new TypeExpression (MutateType (Iterator.OriginalIteratorType), Location);
437 #if GMCS_SOURCE
438 generic_args = new TypeArguments (iterator_type_expr);
439 #endif
441 ArrayList list = new ArrayList ();
442 if (Iterator.IsEnumerable) {
443 enumerable_type = new TypeExpression (
444 TypeManager.ienumerable_type, Location);
445 list.Add (enumerable_type);
447 #if GMCS_SOURCE
448 generic_enumerable_type = new GenericTypeExpr (
449 TypeManager.generic_ienumerable_type,
450 generic_args, Location);
451 list.Add (generic_enumerable_type);
452 #endif
455 enumerator_type = new TypeExpression (
456 TypeManager.ienumerator_type, Location);
457 list.Add (enumerator_type);
459 list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
461 #if GMCS_SOURCE
462 generic_enumerator_type = new GenericTypeExpr (
463 TypeManager.generic_ienumerator_type,
464 generic_args, Location);
465 list.Add (generic_enumerator_type);
466 #endif
468 type_bases = list;
470 return base.ResolveBaseTypes (out base_class);
473 protected override string GetVariableMangledName (LocalInfo local_info)
475 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ();
478 public void DefineIteratorMembers ()
480 pc_field = AddCompilerGeneratedField ("$PC", TypeManager.system_int32_expr);
481 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
483 if (hoisted_params != null) {
485 // Iterators are independent, each GetEnumerator call has to
486 // create same enumerator therefore we have to keep original values
487 // around for re-initialization
489 // TODO: Do it for assigned/modified parameters only
491 hoisted_params_copy = new ArrayList (hoisted_params.Count);
492 foreach (HoistedParameter hp in hoisted_params) {
493 hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
497 #if GMCS_SOURCE
498 Define_Current (true);
499 #endif
500 Define_Current (false);
501 new DisposeMethod (this);
502 Define_Reset ();
504 if (Iterator.IsEnumerable) {
505 MemberName name = new MemberName (
506 new MemberName ("System.Collections.IEnumerable", Location), "GetEnumerator", Location);
508 #if GMCS_SOURCE
509 Method get_enumerator = new IteratorMethod (this, enumerator_type, 0, name);
511 name = new MemberName (
512 new MemberName ("System.Collections.Generic.IEnumerable", generic_args, Location), "GetEnumerator", Location);
513 Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
516 // Just call generic GetEnumerator implementation
518 get_enumerator.Block.AddStatement (
519 new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), new ArrayList (0)), Location));
521 AddMethod (get_enumerator);
522 AddMethod (gget_enumerator);
523 #else
524 AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
525 #endif
529 protected override void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
531 base.EmitHoistedParameters (ec, hoisted);
532 base.EmitHoistedParameters (ec, hoisted_params_copy);
535 void Define_Current (bool is_generic)
537 MemberName left;
538 TypeExpr type;
540 if (is_generic) {
541 left = new MemberName (
542 "System.Collections.Generic.IEnumerator",
543 generic_args, Location);
544 type = iterator_type_expr;
545 } else {
546 left = new MemberName ("System.Collections.IEnumerator", Location);
547 type = TypeManager.system_object_expr;
550 MemberName name = new MemberName (left, "Current", Location);
552 ToplevelBlock get_block = new ToplevelBlock (Location);
553 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
555 Accessor getter = new Accessor (get_block, 0, null, null, Location);
557 Property current = new Property (
558 this, type, Modifiers.DEBUGGER_HIDDEN, name, null, getter, null, false);
559 AddProperty (current);
562 void Define_Reset ()
564 Method reset = new Method (
565 this, null, TypeManager.system_void_expr,
566 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
567 new MemberName ("Reset", Location),
568 ParametersCompiled.EmptyReadOnlyParameters, null);
569 AddMethod (reset);
571 reset.Block = new ToplevelBlock (Location);
573 Type ex_type = TypeManager.CoreLookupType ("System", "NotSupportedException", Kind.Class, true);
574 if (ex_type == null)
575 return;
577 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
582 // Iterators are implemented as hidden anonymous block
584 public class Iterator : AnonymousExpression {
585 public readonly IMethodData OriginalMethod;
586 AnonymousMethodMethod method;
587 public readonly TypeContainer Host;
588 public readonly bool IsEnumerable;
591 // The state as we generate the iterator
593 Label move_next_ok, move_next_error;
594 LocalBuilder skip_finally, current_pc;
596 public LocalBuilder SkipFinally {
597 get { return skip_finally; }
600 public LocalBuilder CurrentPC {
601 get { return current_pc; }
604 public Block Container {
605 get { return OriginalMethod.Block; }
608 public GenericMethod GenericMethod {
609 get { return OriginalMethod.GenericMethod; }
612 public readonly Type OriginalIteratorType;
614 readonly IteratorStorey IteratorHost;
616 public enum State {
617 Running = -3, // Used only in CurrentPC, never stored into $PC
618 Uninitialized = -2,
619 After = -1,
620 Start = 0
623 public void EmitYieldBreak (ILGenerator ig, bool unwind_protect)
625 ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
628 void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
630 ILGenerator ig = ec.ig;
632 ig.Emit (OpCodes.Ldarg_0);
633 ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
635 ig.Emit (OpCodes.Ldarg_0);
636 IntConstant.EmitInt (ig, (int) State.After);
637 ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
639 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
640 ig.Emit (OpCodes.Brtrue, move_next_error);
642 SymbolWriter.StartIteratorBody (ec.ig);
643 original_block.Emit (ec);
644 SymbolWriter.EndIteratorBody (ec.ig);
646 ig.MarkLabel (move_next_error);
647 ig.Emit (OpCodes.Ldc_I4_0);
648 ig.Emit (OpCodes.Ret);
651 internal void EmitMoveNext (EmitContext ec, Block original_block)
653 ILGenerator ig = ec.ig;
655 move_next_ok = ig.DefineLabel ();
656 move_next_error = ig.DefineLabel ();
658 if (resume_points == null) {
659 EmitMoveNext_NoResumePoints (ec, original_block);
660 return;
663 current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
664 ig.Emit (OpCodes.Ldarg_0);
665 ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
666 ig.Emit (OpCodes.Stloc, current_pc);
668 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
669 ig.Emit (OpCodes.Ldarg_0);
670 IntConstant.EmitInt (ig, (int) State.After);
671 ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
673 Label [] labels = new Label [1 + resume_points.Count];
674 labels [0] = ig.DefineLabel ();
676 bool need_skip_finally = false;
677 for (int i = 0; i < resume_points.Count; ++i) {
678 ResumableStatement s = (ResumableStatement) resume_points [i];
679 need_skip_finally |= s is ExceptionStatement;
680 labels [i+1] = s.PrepareForEmit (ec);
683 if (need_skip_finally) {
684 skip_finally = ec.GetTemporaryLocal (TypeManager.bool_type);
685 ig.Emit (OpCodes.Ldc_I4_0);
686 ig.Emit (OpCodes.Stloc, skip_finally);
689 SymbolWriter.StartIteratorDispatcher (ec.ig);
690 ig.Emit (OpCodes.Ldloc, current_pc);
691 ig.Emit (OpCodes.Switch, labels);
693 ig.Emit (OpCodes.Br, move_next_error);
694 SymbolWriter.EndIteratorDispatcher (ec.ig);
696 ig.MarkLabel (labels [0]);
698 SymbolWriter.StartIteratorBody (ec.ig);
699 original_block.Emit (ec);
700 SymbolWriter.EndIteratorBody (ec.ig);
702 SymbolWriter.StartIteratorDispatcher (ec.ig);
704 ig.Emit (OpCodes.Ldarg_0);
705 IntConstant.EmitInt (ig, (int) State.After);
706 ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
708 ig.MarkLabel (move_next_error);
709 ig.Emit (OpCodes.Ldc_I4_0);
710 ig.Emit (OpCodes.Ret);
712 ig.MarkLabel (move_next_ok);
713 ig.Emit (OpCodes.Ldc_I4_1);
714 ig.Emit (OpCodes.Ret);
716 SymbolWriter.EndIteratorDispatcher (ec.ig);
719 public void EmitDispose (EmitContext ec)
721 ILGenerator ig = ec.ig;
723 Label end = ig.DefineLabel ();
725 Label [] labels = null;
726 int n_resume_points = resume_points == null ? 0 : resume_points.Count;
727 for (int i = 0; i < n_resume_points; ++i) {
728 ResumableStatement s = (ResumableStatement) resume_points [i];
729 Label ret = s.PrepareForDispose (ec, end);
730 if (ret.Equals (end) && labels == null)
731 continue;
732 if (labels == null) {
733 labels = new Label [resume_points.Count + 1];
734 for (int j = 0; j <= i; ++j)
735 labels [j] = end;
737 labels [i+1] = ret;
740 if (labels != null) {
741 current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
742 ig.Emit (OpCodes.Ldarg_0);
743 ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
744 ig.Emit (OpCodes.Stloc, current_pc);
747 ig.Emit (OpCodes.Ldarg_0);
748 IntConstant.EmitInt (ig, (int) State.After);
749 ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
751 if (labels != null) {
752 //SymbolWriter.StartIteratorDispatcher (ec.ig);
753 ig.Emit (OpCodes.Ldloc, current_pc);
754 ig.Emit (OpCodes.Switch, labels);
755 //SymbolWriter.EndIteratorDispatcher (ec.ig);
757 foreach (ResumableStatement s in resume_points)
758 s.EmitForDispose (ec, this, end, true);
761 ig.MarkLabel (end);
765 ArrayList resume_points;
766 public int AddResumePoint (ResumableStatement stmt)
768 if (resume_points == null)
769 resume_points = new ArrayList ();
770 resume_points.Add (stmt);
771 return resume_points.Count;
775 // Called back from Yield
777 public void MarkYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
779 ILGenerator ig = ec.ig;
781 // Store the new current
782 ig.Emit (OpCodes.Ldarg_0);
783 expr.Emit (ec);
784 ig.Emit (OpCodes.Stfld, IteratorHost.CurrentField.FieldBuilder);
786 // store resume program-counter
787 ig.Emit (OpCodes.Ldarg_0);
788 IntConstant.EmitInt (ig, resume_pc);
789 ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
791 // mark finally blocks as disabled
792 if (unwind_protect && skip_finally != null) {
793 ig.Emit (OpCodes.Ldc_I4_1);
794 ig.Emit (OpCodes.Stloc, skip_finally);
797 // Return ok
798 ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
800 ig.MarkLabel (resume_point);
803 public override string ContainerType {
804 get { return "iterator"; }
807 public override bool IsIterator {
808 get { return true; }
811 public override AnonymousMethodStorey Storey {
812 get { return IteratorHost; }
816 // Our constructor
818 private Iterator (IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
819 : base (
820 new ToplevelBlock (method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
821 TypeManager.bool_type,
822 method.Location)
824 this.OriginalMethod = method;
825 this.OriginalIteratorType = iterator_type;
826 this.IsEnumerable = is_enumerable;
827 this.Host = host;
829 IteratorHost = Block.ChangeToIterator (this, method.Block);
832 public override string GetSignatureForError ()
834 return OriginalMethod.GetSignatureForError ();
837 public override Expression DoResolve (EmitContext ec)
839 method = new AnonymousMethodMethod (Storey,
840 this, Storey, null, TypeManager.system_boolean_expr,
841 Modifiers.PUBLIC, OriginalMethod.GetSignatureForError (),
842 new MemberName ("MoveNext", Location),
843 ParametersCompiled.EmptyReadOnlyParameters);
845 if (!Compatible (ec))
846 return null;
848 IteratorHost.DefineIteratorMembers ();
850 eclass = ExprClass.Value;
851 type = ec.ReturnType;
852 return this;
855 public override void Emit (EmitContext ec)
858 // Load Iterator storey instance
860 method.Storey.Instance.Emit (ec);
863 // Initialize iterator PC when it's unitialized
865 if (IsEnumerable) {
866 ILGenerator ig = ec.ig;
867 ig.Emit (OpCodes.Dup);
868 IntConstant.EmitInt (ig, (int)State.Uninitialized);
870 FieldInfo field = IteratorHost.PC.FieldBuilder;
871 #if GMCS_SOURCE
872 if (Storey.MemberName.IsGeneric)
873 field = TypeBuilder.GetField (Storey.Instance.Type, field);
874 #endif
875 ig.Emit (OpCodes.Stfld, field);
879 public override Expression CreateExpressionTree (EmitContext ec)
881 throw new NotSupportedException ("ET");
884 public static void CreateIterator (IMethodData method, TypeContainer parent, int modifiers)
886 bool is_enumerable;
887 Type iterator_type;
889 Type ret = method.ReturnType;
890 if (ret == null)
891 return;
893 if (!CheckType (ret, out iterator_type, out is_enumerable)) {
894 Report.Error (1624, method.Location,
895 "The body of `{0}' cannot be an iterator block " +
896 "because `{1}' is not an iterator interface type",
897 method.GetSignatureForError (),
898 TypeManager.CSharpName (ret));
899 return;
902 ParametersCompiled parameters = method.ParameterInfo;
903 for (int i = 0; i < parameters.Count; i++) {
904 Parameter p = parameters [i];
905 Parameter.Modifier mod = p.ModFlags;
906 if ((mod & Parameter.Modifier.ISBYREF) != 0) {
907 Report.Error (1623, p.Location,
908 "Iterators cannot have ref or out parameters");
909 return;
912 if ((mod & Parameter.Modifier.ARGLIST) != 0) {
913 Report.Error (1636, method.Location,
914 "__arglist is not allowed in parameter list of iterators");
915 return;
918 if (parameters.Types [i].IsPointer) {
919 Report.Error (1637, p.Location,
920 "Iterators cannot have unsafe parameters or " +
921 "yield types");
922 return;
926 if ((modifiers & Modifiers.UNSAFE) != 0) {
927 Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
928 return;
931 Iterator iter = new Iterator (method, parent, iterator_type, is_enumerable);
932 iter.Storey.DefineType ();
935 static bool CheckType (Type ret, out Type original_iterator_type, out bool is_enumerable)
937 original_iterator_type = null;
938 is_enumerable = false;
940 if (ret == TypeManager.ienumerable_type) {
941 original_iterator_type = TypeManager.object_type;
942 is_enumerable = true;
943 return true;
945 if (ret == TypeManager.ienumerator_type) {
946 original_iterator_type = TypeManager.object_type;
947 is_enumerable = false;
948 return true;
951 if (!TypeManager.IsGenericType (ret))
952 return false;
954 Type[] args = TypeManager.GetTypeArguments (ret);
955 if (args.Length != 1)
956 return false;
958 Type gt = TypeManager.DropGenericTypeArguments (ret);
959 if (gt == TypeManager.generic_ienumerable_type) {
960 original_iterator_type = args [0];
961 is_enumerable = true;
962 return true;
965 if (gt == TypeManager.generic_ienumerator_type) {
966 original_iterator_type = args [0];
967 is_enumerable = false;
968 return true;
971 return false;