//
// Author:
// Miguel de Icaza (miguel@ximian.com)
+// Marek Safar (marek.safar@gmail.com)
//
-// (C) 2003 Ximian, Inc.
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+// Copyright 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
//
+
// TODO:
// Flow analysis for Yield.
-// Emit calls to base object constructor.
-//
-// Generics note:
-// Current should be defined to return T, and IEnumerator.Current returns object
//
using System;
namespace Mono.CSharp {
- public interface IIteratorContainer {
-
- //
- // Invoked if a yield statement is found in the body
- //
- void SetYields ();
- }
-
- public class Yield : Statement {
+ public class Yield : ResumableStatement {
Expression expr;
- ArrayList finally_blocks;
+ bool unwind_protect;
+
+ int resume_pc;
public Yield (Expression expr, Location l)
{
loc = l;
}
- public static bool CheckContext (EmitContext ec, Location loc, bool isYieldBreak)
+ public static bool CheckContext (EmitContext ec, Location loc)
{
- if (ec.InFinally) {
- Report.Error (1625, loc, "Cannot yield in the body of a " +
- "finally clause");
- return false;
- }
-
- if (ec.InUnsafe) {
+ for (Block block = ec.CurrentBlock; block != null; block = block.Parent) {
+ if (!block.Unsafe)
+ continue;
+
Report.Error (1629, loc, "Unsafe code may not appear in iterators");
return false;
}
- AnonymousContainer am = ec.CurrentAnonymousMethod;
- if ((am != null) && !am.IsIterator){
- Report.Error (1621, loc, "The yield statement cannot be used inside anonymous method blocks");
+ //
+ // We can't use `ec.InUnsafe' here because it's allowed to have an iterator
+ // inside an unsafe class. See test-martin-29.cs for an example.
+ //
+ if (!ec.CurrentAnonymousMethod.IsIterator) {
+ Report.Error (1621, loc,
+ "The yield statement cannot be used inside " +
+ "anonymous method blocks");
return false;
}
- if (ec.CurrentBranching.InTryWithCatch () && (!isYieldBreak || !ec.InCatch)) {
- if (!ec.InCatch)
- Report.Error (1626, loc, "Cannot yield a value in the body of a " +
- "try block with a catch clause");
- else
- Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
- return false;
- }
return true;
}
+
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+ {
+ expr.MutateHoistedGenericType (storey);
+ }
public override bool Resolve (EmitContext ec)
{
if (expr == null)
return false;
- if (!CheckContext (ec, loc, false))
+ Report.Debug (64, "RESOLVE YIELD #1", this, ec, expr, expr.GetType (),
+ ec.CurrentAnonymousMethod, ec.CurrentIterator);
+
+ if (!CheckContext (ec, loc))
return false;
Iterator iterator = ec.CurrentIterator;
-
- if (expr.Type != iterator.IteratorType){
+ if (expr.Type != iterator.OriginalIteratorType) {
expr = Convert.ImplicitConversionRequired (
- ec, expr, iterator.IteratorType, loc);
+ ec, expr, iterator.OriginalIteratorType, loc);
if (expr == null)
return false;
}
- ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
+ if (!ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
+ unwind_protect = ec.CurrentBranching.AddResumePoint (this, loc, out resume_pc);
+
return true;
}
protected override void DoEmit (EmitContext ec)
{
- ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
+ ec.CurrentIterator.MarkYield (ec, expr, resume_pc, unwind_protect, resume_point);
}
- }
- public class YieldBreak : Statement {
+ protected override void CloneTo (CloneContext clonectx, Statement t)
+ {
+ Yield target = (Yield) t;
+ target.expr = expr.Clone (clonectx);
+ }
+ }
+
+ public class YieldBreak : ExitStatement {
public YieldBreak (Location l)
{
loc = l;
}
- public override bool Resolve (EmitContext ec)
+ public override void Error_FinallyClause ()
{
- if (!Yield.CheckContext (ec, loc, true))
- return false;
+ Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
+ }
- ec.CurrentBranching.CurrentUsageVector.Goto ();
- return true;
+ protected override void CloneTo (CloneContext clonectx, Statement target)
+ {
+ throw new NotSupportedException ();
+ }
+
+ protected override bool DoResolve (EmitContext ec)
+ {
+ return Yield.CheckContext (ec, loc);
}
protected override void DoEmit (EmitContext ec)
{
- ec.CurrentIterator.EmitYieldBreak (ec.ig);
+ ec.CurrentIterator.EmitYieldBreak (ec.ig, unwind_protect);
+ }
+
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+ {
+ // nothing to do
}
}
- public class Iterator : Class {
- protected ToplevelBlock original_block;
- protected ToplevelBlock block;
+ //
+ // Wraps method block into iterator wrapper block
+ //
+ class IteratorStatement : Statement
+ {
+ Iterator iterator;
+ ExplicitBlock original_block;
- Type iterator_type;
- TypeExpr iterator_type_expr;
- bool is_enumerable;
- public readonly bool IsStatic;
+ public IteratorStatement (Iterator iterator, ExplicitBlock original_block)
+ {
+ this.iterator = iterator;
+ this.original_block = original_block;
+ this.loc = iterator.Location;
+ }
- //
- // The state as we generate the iterator
- //
- Label move_next_ok, move_next_error;
- ArrayList resume_points = new ArrayList ();
- int pc;
-
- //
- // Context from the original method
- //
- TypeContainer container;
- Type this_type;
- Parameters parameters;
- IMethodData orig_method;
-
- MoveNextMethod move_next_method;
- Constructor ctor;
- CaptureContext cc;
- EmitContext ec;
-
- protected enum State {
- Uninitialized = -2,
- After,
- Running
+ protected override void CloneTo (CloneContext clonectx, Statement target)
+ {
+ IteratorStatement t = (IteratorStatement) target;
+ t.original_block = (ExplicitBlock) original_block.Clone (clonectx);
+ t.iterator = (Iterator) iterator.Clone (clonectx);
}
- static int proxy_count;
+ public override bool Resolve (EmitContext ec)
+ {
+ ec.StartFlowBranching (iterator);
+ bool ok = original_block.Resolve (ec);
+ ec.EndFlowBranching ();
+ return ok;
+ }
- public void EmitYieldBreak (ILGenerator ig)
+ protected override void DoEmit (EmitContext ec)
{
- ig.Emit (OpCodes.Ldarg_0);
- IntConstant.EmitInt (ig, (int) State.After);
- ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
- ig.Emit (OpCodes.Br, move_next_error);
+ iterator.EmitMoveNext (ec, original_block);
}
- public void EmitMoveNext (EmitContext ec)
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
{
- ILGenerator ig = ec.ig;
+ original_block.MutateHoistedGenericType (storey);
+ iterator.MutateHoistedGenericType (storey);
+ }
+ }
- move_next_ok = ig.DefineLabel ();
- move_next_error = ig.DefineLabel ();
+ public class IteratorStorey : AnonymousMethodStorey
+ {
+ class IteratorMethod : Method
+ {
+ readonly IteratorStorey host;
- LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
+ public IteratorMethod (IteratorStorey host, FullNamedExpression returnType, int mod, MemberName name)
+ : base (host, null, returnType, mod | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
+ name, Parameters.EmptyReadOnlyParameters, null)
+ {
+ this.host = host;
- ig.BeginExceptionBlock ();
+ Block = new ToplevelBlock (host.Iterator.Container.Toplevel, null, Location);
+ }
- Label dispatcher = ig.DefineLabel ();
- ig.Emit (OpCodes.Br, dispatcher);
+ public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
+ {
+ EmitContext ec = new EmitContext (
+ this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
- ResumePoint entry_point = new ResumePoint (null);
- resume_points.Add (entry_point);
- entry_point.Define (ig);
+ ec.CurrentAnonymousMethod = host.Iterator;
+ return ec;
+ }
+ }
- ec.EmitTopBlock (orig_method, original_block);
+ class GetEnumeratorMethod : IteratorMethod
+ {
+ sealed class GetEnumeratorStatement : Statement
+ {
+ IteratorStorey host;
+ Expression type;
- EmitYieldBreak (ig);
+ Expression cast;
- ig.MarkLabel (dispatcher);
+ public GetEnumeratorStatement (IteratorStorey host, Expression type)
+ {
+ this.host = host;
+ this.type = type;
+ loc = host.Location;
+ }
- Label [] labels = new Label [resume_points.Count];
- for (int i = 0; i < labels.Length; i++)
- labels [i] = ((ResumePoint) resume_points [i]).Label;
+ protected override void CloneTo (CloneContext clonectx, Statement target)
+ {
+ throw new NotSupportedException ();
+ }
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
- ig.Emit (OpCodes.Switch, labels);
+ public override bool Resolve (EmitContext ec)
+ {
+ type = type.ResolveAsTypeTerminal (ec, false);
+ if ((type == null) || (type.Type == null))
+ return false;
- Label end = ig.DefineLabel ();
+ TypeExpression storey_type_expr = new TypeExpression (host.TypeBuilder, loc);
+ Expression new_storey;
+ ArrayList init = null;
+ if (host.hoisted_this != null) {
+ init = new ArrayList (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
+ HoistedThis ht = host.hoisted_this;
+ FieldExpr from = new FieldExpr (ht.Field.FieldBuilder, loc);
+ from.InstanceExpression = CompilerGeneratedThis.Instance;
+ init.Add (new ElementInitializer (ht.Field.Name, from, loc));
+ }
+
+ if (host.hoisted_params != null) {
+ if (init == null)
+ init = new ArrayList (host.HoistedParameters.Count);
+
+ foreach (HoistedParameter hp in host.HoistedParameters) {
+ FieldExpr from = new FieldExpr (hp.Field.FieldBuilder, loc);
+ from.InstanceExpression = CompilerGeneratedThis.Instance;
+ init.Add (new ElementInitializer (hp.Field.Name, from, loc));
+ }
+ }
+
+ if (init != null) {
+ new_storey = new NewInitialize (storey_type_expr, new ArrayList (0),
+ new CollectionOrObjectInitializers (init, loc), loc);
+ } else {
+ new_storey = new New (storey_type_expr, new ArrayList (0), loc);
+ }
+
+ new_storey = new_storey.Resolve (ec);
+ if (new_storey != null)
+ cast = Convert.ImplicitConversionRequired (ec, new_storey, type.Type, loc);
+
+ if (TypeManager.int_interlocked_compare_exchange == null) {
+ Type t = TypeManager.CoreLookupType ("System.Threading", "Interlocked", Kind.Class, true);
+ if (t != null) {
+ TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
+ t, "CompareExchange", loc, TypeManager.int32_type,
+ TypeManager.int32_type, TypeManager.int32_type);
+ }
+ }
+
+ ec.CurrentBranching.CurrentUsageVector.Goto ();
+ return true;
+ }
- ig.MarkLabel (move_next_error);
- ig.Emit (OpCodes.Ldc_I4_0);
- ig.Emit (OpCodes.Stloc, retval);
- ig.Emit (OpCodes.Leave, end);
+ protected override void DoEmit (EmitContext ec)
+ {
+ ILGenerator ig = ec.ig;
+ Label label_init = ig.DefineLabel ();
- ig.MarkLabel (move_next_ok);
- ig.Emit (OpCodes.Ldc_I4_1);
- ig.Emit (OpCodes.Stloc, retval);
- ig.Emit (OpCodes.Leave, end);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldflda, host.PC.FieldBuilder);
+ ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Start);
+ ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Uninitialized);
+ ig.Emit (OpCodes.Call, TypeManager.int_interlocked_compare_exchange);
- ig.BeginFaultBlock ();
+ ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Uninitialized);
+ ig.Emit (OpCodes.Bne_Un, label_init);
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Callvirt, dispose.MethodBuilder);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ret);
- ig.EndExceptionBlock ();
+ ig.MarkLabel (label_init);
- ig.MarkLabel (end);
- ig.Emit (OpCodes.Ldloc, retval);
- ig.Emit (OpCodes.Ret);
- }
+ cast.Emit (ec);
+ ig.Emit (OpCodes.Ret);
+ }
- public void EmitDispose (EmitContext ec)
- {
- ILGenerator ig = ec.ig;
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+ {
+ throw new NotSupportedException ();
+ }
+ }
- Label end = ig.DefineLabel ();
- Label dispatcher = ig.DefineLabel ();
- ig.Emit (OpCodes.Br, dispatcher);
+ public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
+ : base (host, returnType, 0, name)
+ {
+ Block.AddStatement (new GetEnumeratorStatement (host, type_name));
+ }
+ }
- Label [] labels = new Label [resume_points.Count];
- for (int i = 0; i < labels.Length; i++) {
- ResumePoint point = (ResumePoint) resume_points [i];
+ class DisposeMethod : IteratorMethod
+ {
+ sealed class DisposeMethodStatement : Statement
+ {
+ Iterator iterator;
- if (point.FinallyBlocks == null) {
- labels [i] = end;
- continue;
+ public DisposeMethodStatement (Iterator iterator)
+ {
+ this.iterator = iterator;
+ this.loc = iterator.Location;
}
- labels [i] = ig.DefineLabel ();
- ig.MarkLabel (labels [i]);
+ protected override void CloneTo (CloneContext clonectx, Statement target)
+ {
+ throw new NotSupportedException ();
+ }
- ig.BeginExceptionBlock ();
- ig.BeginFinallyBlock ();
+ public override bool Resolve (EmitContext ec)
+ {
+ return true;
+ }
- foreach (ExceptionStatement stmt in point.FinallyBlocks) {
- if (stmt != null)
- stmt.EmitFinally (ec);
+ protected override void DoEmit (EmitContext ec)
+ {
+ iterator.EmitDispose (ec);
}
- ig.EndExceptionBlock ();
- ig.Emit (OpCodes.Br, end);
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+ {
+ throw new NotSupportedException ();
+ }
}
-
- ig.MarkLabel (dispatcher);
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
- ig.Emit (OpCodes.Switch, labels);
- ig.Emit (OpCodes.Ldarg_0);
- IntConstant.EmitInt (ig, (int) State.After);
- ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
+ public DisposeMethod (IteratorStorey host)
+ : base (host, TypeManager.system_void_expr, Modifiers.PUBLIC, new MemberName ("Dispose", host.Location))
+ {
+ host.AddMethod (this);
- ig.MarkLabel (end);
+ Block = new ToplevelBlock (host.Iterator.Container, null, Location);
+ Block.AddStatement (new DisposeMethodStatement (host.Iterator));
+ }
}
- protected class ResumePoint
+ //
+ // Uses Method as method info
+ //
+ class DynamicMethodGroupExpr : MethodGroupExpr
{
- public Label Label;
- public readonly ExceptionStatement[] FinallyBlocks;
+ readonly Method method;
- public ResumePoint (ArrayList list)
+ public DynamicMethodGroupExpr (Method method, Location loc)
+ : base (null, loc)
{
- if (list != null) {
- FinallyBlocks = new ExceptionStatement [list.Count];
- list.CopyTo (FinallyBlocks, 0);
- }
+ this.method = method;
}
- public void Define (ILGenerator ig)
+ public override Expression DoResolve (EmitContext ec)
{
- Label = ig.DefineLabel ();
- ig.MarkLabel (Label);
+ Methods = new MethodBase [] { method.MethodBuilder };
+ type = method.Parent.TypeBuilder;
+ InstanceExpression = new CompilerGeneratedThis (type, Location);
+ return base.DoResolve (ec);
}
}
- //
- // Called back from Yield
- //
- public void MarkYield (EmitContext ec, Expression expr,
- ArrayList finally_blocks)
- {
- ILGenerator ig = ec.ig;
-
- // Store the new current
- ig.Emit (OpCodes.Ldarg_0);
- expr.Emit (ec);
- ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
+ public readonly Iterator Iterator;
- // increment pc
- pc++;
- ig.Emit (OpCodes.Ldarg_0);
- IntConstant.EmitInt (ig, pc);
- ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
+ TypeExpr iterator_type_expr;
+ Field pc_field;
+ Field current_field;
- // Return ok
- ig.Emit (OpCodes.Br, move_next_ok);
+ TypeExpr enumerator_type;
+ TypeExpr enumerable_type;
+#if GMCS_SOURCE
+ TypeArguments generic_args;
+ TypeExpr generic_enumerator_type;
+ TypeExpr generic_enumerable_type;
+#else
+ const TypeArguments generic_args = null;
+#endif
- ResumePoint point = new ResumePoint (finally_blocks);
- resume_points.Add (point);
- point.Define (ig);
- }
+ int local_name_idx;
- public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
+ public IteratorStorey (Iterator iterator)
+ : base (iterator.Container.Toplevel, iterator.Host,
+ iterator.OriginalMethod as MemberBase, iterator.GenericMethod, "Iterator")
{
- ILGenerator ig = ec.ig;
-
- // increment pc
- pc++;
- ig.Emit (OpCodes.Ldarg_0);
- IntConstant.EmitInt (ig, pc);
- ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
-
- ResumePoint point = new ResumePoint (finally_blocks);
- resume_points.Add (point);
- point.Define (ig);
+ this.Iterator = iterator;
+ HasHoistedVariables = true;
}
- private static MemberName MakeProxyName (string name, Location loc)
- {
- int pos = name.LastIndexOf ('.');
- if (pos > 0)
- name = name.Substring (pos + 1);
-
- return new MemberName ("<" + name + ">__" + (proxy_count++), loc);
+ public Field PC {
+ get { return pc_field; }
}
- //
- // Our constructor
- //
- public Iterator (IMethodData m_container, DeclSpace parent,
- int modifiers)
- : base (parent.NamespaceEntry, parent, MakeProxyName (m_container.MethodName.Name, m_container.Location),
- (modifiers & Modifiers.UNSAFE) | Modifiers.PRIVATE, null)
- {
- this.orig_method = m_container;
-
- this.container = ((TypeContainer) parent).PartialContainer;
- this.parameters = m_container.ParameterInfo;
- this.original_block = orig_method.Block;
- this.block = new ToplevelBlock (orig_method.Block, parameters, orig_method.Location);
-
- IsStatic = (modifiers & Modifiers.STATIC) != 0;
+ public Field CurrentField {
+ get { return current_field; }
}
- public AnonymousContainer Host {
- get { return move_next_method; }
+ public ArrayList HoistedParameters {
+ get { return hoisted_params; }
}
- public bool DefineIterator ()
+ protected override TypeExpr [] ResolveBaseTypes (out TypeExpr base_class)
{
- ec = new EmitContext (this, this, Mono.CSharp.Location.Null, null, null, ModFlags);
- ec.CurrentAnonymousMethod = move_next_method;
- ec.CurrentIterator = this;
- ec.InIterator = true;
-
- if (!CheckType ()) {
- Report.Error (1624, Location,
- "The body of `{0}' cannot be an iterator block because `{1}' is not an iterator interface type",
- orig_method.GetSignatureForError (), TypeManager.CSharpName (orig_method.ReturnType));
- return false;
- }
+ iterator_type_expr = new TypeExpression (MutateType (Iterator.OriginalIteratorType), Location);
- for (int i = 0; i < parameters.Count; i++){
- Parameter.Modifier mod = parameters.ParameterModifier (i);
- if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
- Report.Error (
- 1623, Location,
- "Iterators cannot have ref or out parameters");
- return false;
- }
+#if GMCS_SOURCE
+ generic_args = new TypeArguments (Location);
+ generic_args.Add (iterator_type_expr);
+#endif
- if ((mod & Parameter.Modifier.ARGLIST) != 0) {
- Report.Error (1636, Location, "__arglist is not allowed in parameter list of iterators");
- return false;
- }
+ ArrayList list = new ArrayList ();
+ if (Iterator.IsEnumerable) {
+ enumerable_type = new TypeExpression (
+ TypeManager.ienumerable_type, Location);
+ list.Add (enumerable_type);
- if (parameters.ParameterType (i).IsPointer) {
- Report.Error (1637, Location, "Iterators cannot have unsafe parameters or yield types");
- return false;
- }
+#if GMCS_SOURCE
+ generic_enumerable_type = new ConstructedType (
+ TypeManager.generic_ienumerable_type,
+ generic_args, Location);
+ list.Add (generic_enumerable_type);
+#endif
}
- this_type = container.TypeBuilder;
+ enumerator_type = new TypeExpression (
+ TypeManager.ienumerator_type, Location);
+ list.Add (enumerator_type);
- ArrayList list = new ArrayList ();
- if (is_enumerable)
- list.Add (new TypeExpression (
- TypeManager.ienumerable_type, Location));
- list.Add (new TypeExpression (TypeManager.ienumerator_type, Location));
list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
- iterator_type_expr = new TypeExpression (iterator_type, Location);
+#if GMCS_SOURCE
+ generic_enumerator_type = new ConstructedType (
+ TypeManager.generic_ienumerator_type,
+ generic_args, Location);
+ list.Add (generic_enumerator_type);
+#endif
- container.AddIterator (this);
+ type_bases = list;
- Bases = list;
- orig_method.Block = block;
- return true;
+ return base.ResolveBaseTypes (out base_class);
}
- protected override bool DoDefineMembers ()
+ protected override string GetVariableMangledName (LocalInfo local_info)
{
- ec.InIterator = true;
- ec.CurrentIterator = this;
- ec.CurrentAnonymousMethod = move_next_method;
- ec.capture_context = cc;
-
- if (!base.DoDefineMembers ())
- return false;
-
- return true;
+ return "<" + local_info.Name + ">__" + local_name_idx++.ToString ();
}
- public override bool Define ()
+ public void DefineIteratorMembers ()
{
- if (!base.Define ())
- return false;
-
- ec.InIterator = true;
- ec.CurrentIterator = this;
- ec.CurrentAnonymousMethod = move_next_method;
- ec.capture_context = cc;
- ec.TypeContainer = ec.TypeContainer.Parent;
+ pc_field = AddCompilerGeneratedField ("$PC", TypeManager.system_int32_expr);
+ current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
- ec.ContainerType = ec.TypeContainer.TypeBuilder;
-
- ec.ig = move_next_method.method.MethodBuilder.GetILGenerator ();
-
- if (!ctor.Define ())
- return false;
+#if GMCS_SOURCE
+ Define_Current (true);
+#endif
+ Define_Current (false);
+ new DisposeMethod (this);
+ Define_Reset ();
- bool unreachable;
+ if (Iterator.IsEnumerable) {
+ MemberName name = new MemberName (
+ new MemberName ("System.Collections.IEnumerable", Location), "GetEnumerator", Location);
- if (!ec.ResolveTopBlock (null, original_block, parameters, orig_method, out unreachable))
- return false;
+#if GMCS_SOURCE
+ Method get_enumerator = new IteratorMethod (this, enumerator_type, 0, name);
- if (!ec.ResolveTopBlock (null, block, parameters, orig_method, out unreachable))
- return false;
+ name = new MemberName (
+ new MemberName ("System.Collections.Generic.IEnumerable", generic_args, Location), "GetEnumerator", Location);
+ Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
- original_block.CompleteContexts ();
+ //
+ // Just call generic GetEnumerator implementation
+ //
+ get_enumerator.Block.AddStatement (
+ new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), new ArrayList (0)), Location));
- cc.EmitAnonymousHelperClasses (ec);
+ AddMethod (get_enumerator);
+ AddMethod (gget_enumerator);
+#else
+ AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
+#endif
+ }
- return true;
+ DoResolveMembers ();
}
- //
- // Returns the new block for the method, or null on failure
- //
- protected override bool DefineNestedTypes ()
+ void Define_Current (bool is_generic)
{
- Define_Fields ();
- Define_Current ();
- Define_MoveNext ();
- Define_Reset ();
- Define_Dispose ();
+ MemberName left;
+ TypeExpr type;
- Create_Block ();
+ if (is_generic) {
+ left = new MemberName (
+ "System.Collections.Generic.IEnumerator",
+ generic_args, Location);
+ type = iterator_type_expr;
+ } else {
+ left = new MemberName ("System.Collections.IEnumerator", Location);
+ type = TypeManager.system_object_expr;
+ }
- Define_Constructor ();
+ MemberName name = new MemberName (left, "Current", null, Location);
- if (is_enumerable)
- Define_GetEnumerator ();
+ ToplevelBlock get_block = new ToplevelBlock (Location);
+ get_block.AddStatement (new CurrentBlock (this, is_generic));
- return base.DefineNestedTypes ();
- }
+ Accessor getter = new Accessor (get_block, 0, null, null, Location);
- Field pc_field;
- Field current_field;
- Method dispose;
+ Property current = new Property (
+ this, type, Modifiers.DEBUGGER_HIDDEN, name, null, getter, null, false);
+ AddProperty (current);
+ }
- void Create_Block ()
+ void Define_Reset ()
{
- original_block.SetHaveAnonymousMethods (Location, move_next_method);
- block.SetHaveAnonymousMethods (Location, move_next_method);
+ Method reset = new Method (
+ this, null, TypeManager.system_void_expr,
+ Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
+ new MemberName ("Reset", Location),
+ Parameters.EmptyReadOnlyParameters, null);
+ AddMethod (reset);
- cc = original_block.CaptureContext;
+ reset.Block = new ToplevelBlock (Location);
+ reset.Block.AddStatement (Create_ThrowNotSupported ());
+ }
- int first = IsStatic ? 0 : 1;
+ Statement Create_ThrowNotSupported ()
+ {
+ TypeExpr ex_type = new TypeLookupExpression ("System.NotSupportedException");
- ArrayList args = new ArrayList ();
- if (!IsStatic) {
- Type t = container.TypeBuilder;
- args.Add (new Argument (
- new ThisParameterReference (t, Location)));
- cc.CaptureThis (move_next_method);
- }
+ return new Throw (new New (ex_type, null, Location), Location);
+ }
- args.Add (new Argument (new BoolLiteral (false, Location)));
+ protected class CurrentBlock : Statement {
+ IteratorStorey host;
+ bool is_generic;
- for (int i = 0; i < parameters.Count; i++) {
- Type t = parameters.ParameterType (i);
- string name = parameters.ParameterName (i);
+ public CurrentBlock (IteratorStorey host, bool is_generic)
+ {
+ this.host = host;
+ this.is_generic = is_generic;
+ loc = host.Location;
+ }
- args.Add (new Argument (
- new SimpleParameterReference (t, first + i, Location)));
+ protected override void CloneTo (CloneContext clonectx, Statement target)
+ {
+ throw new NotSupportedException ();
+ }
- cc.AddParameterToContext (move_next_method, name, t, first + i);
+ public override bool Resolve (EmitContext ec)
+ {
+ // We emit a 'ret', so prevent the enclosing TopLevelBlock from emitting one too
+ ec.CurrentBranching.CurrentUsageVector.Goto ();
+ return true;
}
- Expression new_expr = new New (
- new TypeExpression (TypeBuilder, Location), args, Location);
+ protected override void DoEmit (EmitContext ec)
+ {
+ ILGenerator ig = ec.ig;
- block.AddStatement (new NoCheckReturn (new_expr, Location));
- }
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldfld, host.CurrentField.FieldBuilder);
+ if (!is_generic)
+ ig.Emit (OpCodes.Box, host.CurrentField.MemberType);
+ ig.Emit (OpCodes.Ret);
+ }
- void Define_Fields ()
- {
- pc_field = new Field (
- this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "$PC",
- null, Location);
- AddField (pc_field);
-
- current_field = new Field (
- this, iterator_type_expr, Modifiers.PRIVATE, "$current",
- null, Location);
- AddField (current_field);
+ public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+ {
+ throw new NotSupportedException ();
+ }
}
+ }
- void Define_Constructor ()
- {
- Parameters ctor_params;
-
- ArrayList list = new ArrayList ();
-
- if (!IsStatic)
- list.Add (new Parameter (
- new TypeExpression (container.TypeBuilder, Location),
- "this", Parameter.Modifier.NONE,
- null, Location));
- list.Add (new Parameter (
- TypeManager.bool_type, "initialized",
- Parameter.Modifier.NONE, null, Location));
-
- Parameter[] old_fixed = parameters.FixedParameters;
- list.AddRange (old_fixed);
+ //
+ // Iterators are implemented as hidden anonymous block
+ //
+ public class Iterator : AnonymousExpression {
+ public readonly IMethodData OriginalMethod;
+ AnonymousMethodMethod method;
+ public readonly TypeContainer Host;
+ public readonly bool IsEnumerable;
- Parameter[] fixed_params = new Parameter [list.Count];
- list.CopyTo (fixed_params);
+ //
+ // The state as we generate the iterator
+ //
+ Label move_next_ok, move_next_error;
+ LocalBuilder skip_finally, current_pc;
- ctor_params = new Parameters (fixed_params);
+ public LocalBuilder SkipFinally {
+ get { return skip_finally; }
+ }
- ctor = new Constructor (
- this, Name, Modifiers.PUBLIC, ctor_params,
- new GeneratedBaseInitializer (Location),
- Location);
- AddConstructor (ctor);
+ public LocalBuilder CurrentPC {
+ get { return current_pc; }
+ }
- ctor.Block = new ToplevelBlock (block, parameters, Location);
+ public Block Container {
+ get { return OriginalMethod.Block; }
+ }
- int first = IsStatic ? 2 : 3;
+ public GenericMethod GenericMethod {
+ get { return OriginalMethod.GenericMethod; }
+ }
- State initial = is_enumerable ? State.Uninitialized : State.Running;
- ctor.Block.AddStatement (new SetState (this, initial, Location));
+ public readonly Type OriginalIteratorType;
- ctor.Block.AddStatement (new If (
- new SimpleParameterReference (
- TypeManager.bool_type, first - 1, Location),
- new SetState (this, State.Running, Location),
- Location));
+ readonly IteratorStorey IteratorHost;
- ctor.Block.AddStatement (new InitScope (this, Location));
+ public enum State {
+ Running = -3, // Used only in CurrentPC, never stored into $PC
+ Uninitialized = -2,
+ After = -1,
+ Start = 0
}
- Statement Create_ThrowInvalidOperation ()
+ public override void AddStoreyReference (AnonymousMethodStorey storey)
{
- TypeExpr ex_type = new TypeExpression (
- TypeManager.invalid_operation_exception_type, Location);
-
- return new Throw (new New (ex_type, null, Location), Location);
+ // do nothing
}
- Statement Create_ThrowNotSupported ()
+ public void EmitYieldBreak (ILGenerator ig, bool unwind_protect)
{
- TypeExpr ex_type = new TypeExpression (
- TypeManager.not_supported_exception_type, Location);
-
- return new Throw (new New (ex_type, null, Location), Location);
+ ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
}
- void Define_Current ()
+ void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
{
- ToplevelBlock get_block = new ToplevelBlock (
- block, parameters, Location);
- MemberName left = new MemberName ("System.Collections.IEnumerator");
- MemberName name = new MemberName (left, "Current", Location);
-
- get_block.AddStatement (new If (
- new Binary (
- Binary.Operator.LessThanOrEqual,
- new FieldExpression (this, pc_field),
- new IntLiteral ((int) State.Running, pc_field.Location)),
- Create_ThrowInvalidOperation (),
- new Return (
- new FieldExpression (this, current_field), Location),
- Location));
-
- Accessor getter = new Accessor (get_block, 0, null, Location);
+ ILGenerator ig = ec.ig;
- Property current = new Property (
- this, iterator_type_expr, 0,
- false, name, null, getter, null);
- AddProperty (current);
- }
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
- void Define_MoveNext ()
- {
- move_next_method = new MoveNextMethod (this, Location);
+ ig.Emit (OpCodes.Ldarg_0);
+ IntConstant.EmitInt (ig, (int) State.After);
+ ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
- original_block.ReParent (block, move_next_method);
+ // We only care if the PC is zero (start executing) or non-zero (don't do anything)
+ ig.Emit (OpCodes.Brtrue, move_next_error);
- move_next_method.CreateMethod (ec);
+ SymbolWriter.StartIteratorBody (ec.ig);
+ original_block.Emit (ec);
+ SymbolWriter.EndIteratorBody (ec.ig);
- AddMethod (move_next_method.method);
+ ig.MarkLabel (move_next_error);
+ ig.Emit (OpCodes.Ldc_I4_0);
+ ig.Emit (OpCodes.Ret);
}
- void Define_GetEnumerator ()
+ internal void EmitMoveNext (EmitContext ec, Block original_block)
{
- MemberName left = new MemberName ("System.Collections.IEnumerable");
-
- MemberName name = new MemberName (left, "GetEnumerator", Location);
+ ILGenerator ig = ec.ig;
- Method get_enumerator = new Method (
- this,
- new TypeExpression (TypeManager.ienumerator_type, Location),
- 0, false, name,
- Parameters.EmptyReadOnlyParameters, null);
+ move_next_ok = ig.DefineLabel ();
+ move_next_error = ig.DefineLabel ();
- //
- // We call append instead of add, as we need to make sure that
- // this method is resolved after the MoveNext method, as that one
- // triggers the computation of the AnonymousMethod Scope, which is
- // required during the code generation of the enumerator
- //
- AppendMethod (get_enumerator);
-
- get_enumerator.Block = new ToplevelBlock (
- block, parameters, Location);
-
- get_enumerator.Block.SetHaveAnonymousMethods (Location, move_next_method);
-
- Expression ce = new MemberAccess (
- new SimpleName ("System.Threading.Interlocked", Location),
- "CompareExchange");
-
- Expression pc = new FieldExpression (this, pc_field);
- Expression before = new IntLiteral ((int) State.Running, Location);
- Expression uninitialized = new IntLiteral ((int) State.Uninitialized, Location);
-
- ArrayList args = new ArrayList ();
- args.Add (new Argument (pc, Argument.AType.Ref));
- args.Add (new Argument (before, Argument.AType.Expression));
- args.Add (new Argument (uninitialized, Argument.AType.Expression));
-
- get_enumerator.Block.AddStatement (new If (
- new Binary (
- Binary.Operator.Equality,
- new Invocation (ce, args),
- uninitialized),
- new Return (new ThisParameterReference (
- TypeManager.ienumerator_type, Location),
- Location),
- Location));
-
- args = new ArrayList ();
- if (!IsStatic) {
- args.Add (new Argument (new CapturedThisReference (this, Location)));
+ if (resume_points == null) {
+ EmitMoveNext_NoResumePoints (ec, original_block);
+ return;
}
- args.Add (new Argument (new BoolLiteral (true, Location)));
-
- for (int i = 0; i < parameters.Count; i++) {
- Expression cp = new CapturedParameterReference (
- this, parameters.ParameterType (i),
- parameters.ParameterName (i), Location);
- args.Add (new Argument (cp));
- }
+ current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
+ ig.Emit (OpCodes.Stloc, current_pc);
- Expression new_expr = new New (
- new TypeExpression (TypeBuilder, Location), args, Location);
- get_enumerator.Block.AddStatement (new Return (new_expr, Location));
- }
+ // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
+ ig.Emit (OpCodes.Ldarg_0);
+ IntConstant.EmitInt (ig, (int) State.After);
+ ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
- protected class SimpleParameterReference : Expression
- {
- int idx;
+ Label [] labels = new Label [1 + resume_points.Count];
+ labels [0] = ig.DefineLabel ();
- public SimpleParameterReference (Type type, int idx, Location loc)
- {
- this.idx = idx;
- this.loc = loc;
- this.type = type;
- eclass = ExprClass.Variable;
+ bool need_skip_finally = false;
+ for (int i = 0; i < resume_points.Count; ++i) {
+ ResumableStatement s = (ResumableStatement) resume_points [i];
+ need_skip_finally |= s is ExceptionStatement;
+ labels [i+1] = s.PrepareForEmit (ec);
}
- public override Expression DoResolve (EmitContext ec)
- {
- return this;
+ if (need_skip_finally) {
+ skip_finally = ec.GetTemporaryLocal (TypeManager.bool_type);
+ ig.Emit (OpCodes.Ldc_I4_0);
+ ig.Emit (OpCodes.Stloc, skip_finally);
}
- public override void Emit (EmitContext ec)
- {
- DoEmit (ec);
- }
+ SymbolWriter.StartIteratorDispatcher (ec.ig);
+ ig.Emit (OpCodes.Ldloc, current_pc);
+ ig.Emit (OpCodes.Switch, labels);
- protected virtual void DoEmit (EmitContext ec)
- {
- ParameterReference.EmitLdArg (ec.ig, idx);
- }
- }
+ ig.Emit (OpCodes.Br, move_next_error);
+ SymbolWriter.EndIteratorDispatcher (ec.ig);
- protected class ThisParameterReference : SimpleParameterReference, IMemoryLocation
- {
- public ThisParameterReference (Type type, Location loc)
- : base (type, 0, loc)
- { }
+ ig.MarkLabel (labels [0]);
- protected override void DoEmit (EmitContext ec)
- {
- base.DoEmit (ec);
- if (ec.TypeContainer is Struct)
- ec.ig.Emit (OpCodes.Ldobj, type);
- }
+ SymbolWriter.StartIteratorBody (ec.ig);
+ original_block.Emit (ec);
+ SymbolWriter.EndIteratorBody (ec.ig);
- public void AddressOf (EmitContext ec, AddressOp mode)
- {
- if (ec.TypeContainer is Struct)
- ec.ig.Emit (OpCodes.Ldarga, 0);
- else
- ec.ig.Emit (OpCodes.Ldarg, 0);
- }
- }
-
- protected class CapturedParameterReference : Expression
- {
- Iterator iterator;
- string name;
+ SymbolWriter.StartIteratorDispatcher (ec.ig);
- public CapturedParameterReference (Iterator iterator, Type type,
- string name, Location loc)
- {
- this.iterator = iterator;
- this.loc = loc;
- this.type = type;
- this.name = name;
- eclass = ExprClass.Variable;
- }
+ ig.Emit (OpCodes.Ldarg_0);
+ IntConstant.EmitInt (ig, (int) State.After);
+ ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
- public override Expression DoResolve (EmitContext ec)
- {
- return this;
- }
+ ig.MarkLabel (move_next_error);
+ ig.Emit (OpCodes.Ldc_I4_0);
+ ig.Emit (OpCodes.Ret);
- public override void Emit (EmitContext ec)
- {
- ec.CurrentAnonymousMethod = iterator.move_next_method;
+ ig.MarkLabel (move_next_ok);
+ ig.Emit (OpCodes.Ldc_I4_1);
+ ig.Emit (OpCodes.Ret);
- LocalTemporary dummy = null;
-
- iterator.cc.EmitParameter (ec, name, false, false, ref dummy);
- }
+ SymbolWriter.EndIteratorDispatcher (ec.ig);
}
- protected class CapturedThisReference : Expression
+ public void EmitDispose (EmitContext ec)
{
- public CapturedThisReference (Iterator iterator, Location loc)
- {
- this.loc = loc;
- this.type = iterator.this_type;
- eclass = ExprClass.Variable;
- }
+ ILGenerator ig = ec.ig;
- public override Expression DoResolve (EmitContext ec)
- {
- return this;
- }
+ Label end = ig.DefineLabel ();
- public override void Emit (EmitContext ec)
- {
- ec.EmitThis (false);
+ Label [] labels = null;
+ int n_resume_points = resume_points == null ? 0 : resume_points.Count;
+ for (int i = 0; i < n_resume_points; ++i) {
+ ResumableStatement s = (ResumableStatement) resume_points [i];
+ Label ret = s.PrepareForDispose (ec, end);
+ if (ret.Equals (end) && labels == null)
+ continue;
+ if (labels == null) {
+ labels = new Label [resume_points.Count + 1];
+ for (int j = 0; j <= i; ++j)
+ labels [j] = end;
+ }
+ labels [i+1] = ret;
}
- }
-
- protected class FieldExpression : Expression
- {
- Iterator iterator;
- Field field;
- public FieldExpression (Iterator iterator, Field field)
- {
- this.iterator = iterator;
- this.field = field;
- this.loc = iterator.Location;
+ if (labels != null) {
+ current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
+ ig.Emit (OpCodes.Stloc, current_pc);
}
- public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
- {
- FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
- fexpr.InstanceExpression = new ThisParameterReference (
- iterator.this_type, loc);
- return fexpr.ResolveLValue (ec, right_side, loc);
- }
+ ig.Emit (OpCodes.Ldarg_0);
+ IntConstant.EmitInt (ig, (int) State.After);
+ ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
- public override Expression DoResolve (EmitContext ec)
- {
- FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
- fexpr.InstanceExpression = new ThisParameterReference (
- iterator.this_type, loc);
- return fexpr.Resolve (ec);
- }
+ if (labels != null) {
+ //SymbolWriter.StartIteratorDispatcher (ec.ig);
+ ig.Emit (OpCodes.Ldloc, current_pc);
+ ig.Emit (OpCodes.Switch, labels);
+ //SymbolWriter.EndIteratorDispatcher (ec.ig);
- public override void Emit (EmitContext ec)
- {
- throw new InvalidOperationException ();
+ foreach (ResumableStatement s in resume_points)
+ s.EmitForDispose (ec, this, end, true);
}
- }
- protected class MoveNextMethod : AnonymousContainer
- {
- Iterator iterator;
-
- public MoveNextMethod (Iterator iterator, Location loc)
- : base (iterator.parameters, iterator.original_block, loc)
- {
- this.iterator = iterator;
- }
+ ig.MarkLabel (end);
+ }
- protected override bool CreateMethodHost (EmitContext ec)
- {
- method = new Method (
- iterator, TypeManager.system_boolean_expr,
- Modifiers.PUBLIC, false, new MemberName ("MoveNext", loc),
- Parameters.EmptyReadOnlyParameters, null);
- method.Block = Block;
+ ArrayList resume_points;
+ public int AddResumePoint (ResumableStatement stmt)
+ {
+ if (resume_points == null)
+ resume_points = new ArrayList ();
+ resume_points.Add (stmt);
+ return resume_points.Count;
+ }
- MoveNextStatement inline = new MoveNextStatement (iterator, loc);
- Block.AddStatement (inline);
+ //
+ // Called back from Yield
+ //
+ public void MarkYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
+ {
+ ILGenerator ig = ec.ig;
- return true;
- }
+ // Store the new current
+ ig.Emit (OpCodes.Ldarg_0);
+ expr.Emit (ec);
+ ig.Emit (OpCodes.Stfld, IteratorHost.CurrentField.FieldBuilder);
- public bool CreateMethod (EmitContext ec)
- {
- return CreateMethodHost (ec);
- }
+ // store resume program-counter
+ ig.Emit (OpCodes.Ldarg_0);
+ IntConstant.EmitInt (ig, resume_pc);
+ ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
- public void ComputeHost ()
- {
- ComputeMethodHost ();
- }
-
- public override bool IsIterator {
- get { return true; }
+ // mark finally blocks as disabled
+ if (unwind_protect && skip_finally != null) {
+ ig.Emit (OpCodes.Ldc_I4_1);
+ ig.Emit (OpCodes.Stloc, skip_finally);
}
- public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
- {
- scope.ScopeTypeBuilder = iterator.TypeBuilder;
- scope.ScopeConstructor = iterator.ctor.ConstructorBuilder;
- }
+ // Return ok
+ ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
- public override void Emit (EmitContext ec)
- {
- throw new InternalErrorException ();
- }
+ ig.MarkLabel (resume_point);
}
- protected class MoveNextStatement : Statement {
- Iterator iterator;
-
- public MoveNextStatement (Iterator iterator, Location loc)
- {
- this.loc = loc;
- this.iterator = iterator;
- }
-
- protected override void DoEmit (EmitContext ec)
- {
- iterator.move_next_method.ComputeHost ();
-
- ec.CurrentIterator = iterator;
- ec.CurrentAnonymousMethod = iterator.move_next_method;
- ec.InIterator = true;
-
- iterator.EmitMoveNext (ec);
- }
+ public override string ContainerType {
+ get { return "iterator"; }
}
- protected class DisposeMethod : Statement {
- Iterator iterator;
-
- public DisposeMethod (Iterator iterator, Location loc)
- {
- this.loc = loc;
- this.iterator = iterator;
- }
-
- public override bool Resolve (EmitContext ec)
- {
- return true;
- }
-
- protected override void DoEmit (EmitContext ec)
- {
- iterator.EmitDispose (ec);
- }
+ public override bool IsIterator {
+ get { return true; }
}
- protected class StatementList : Statement {
- ArrayList statements;
-
- public StatementList (Location loc)
- {
- this.loc = loc;
- statements = new ArrayList ();
- }
-
- public void Add (Statement statement)
- {
- statements.Add (statement);
- }
+ public override AnonymousMethodStorey Storey {
+ get { return IteratorHost; }
+ }
- public override bool Resolve (EmitContext ec)
- {
- foreach (Statement stmt in statements) {
- if (!stmt.Resolve (ec))
- return false;
- }
+ //
+ // Our constructor
+ //
+ private Iterator (IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
+ : base (
+ new ToplevelBlock (method.Block, Parameters.EmptyReadOnlyParameters, method.Block.StartLocation),
+ TypeManager.bool_type,
+ method.Location)
+ {
+ this.OriginalMethod = method;
+ this.OriginalIteratorType = iterator_type;
+ this.IsEnumerable = is_enumerable;
+ this.Host = host;
- return true;
- }
+ IteratorHost = Block.ChangeToIterator (this, method.Block);
+ }
- protected override void DoEmit (EmitContext ec)
- {
- foreach (Statement stmt in statements)
- stmt.Emit (ec);
- }
+ public override string GetSignatureForError ()
+ {
+ return OriginalMethod.GetSignatureForError ();
}
- protected class SetState : Statement
+ public override Expression DoResolve (EmitContext ec)
{
- Iterator iterator;
- State state;
+ method = new AnonymousMethodMethod (Storey,
+ this, Storey, null, TypeManager.system_boolean_expr,
+ Modifiers.PUBLIC, OriginalMethod.GetSignatureForError (),
+ new MemberName ("MoveNext", Location),
+ Parameters.EmptyReadOnlyParameters);
- public SetState (Iterator iterator, State state, Location loc)
- {
- this.iterator = iterator;
- this.state = state;
- this.loc = loc;
- }
+ if (!Compatible (ec))
+ return null;
- public override bool Resolve (EmitContext ec)
- {
- return true;
- }
+ IteratorHost.DefineIteratorMembers ();
- protected override void DoEmit (EmitContext ec)
- {
- ec.ig.Emit (OpCodes.Ldarg_0);
- IntConstant.EmitInt (ec.ig, (int) state);
- ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
- }
+ eclass = ExprClass.Value;
+ type = ec.ReturnType;
+ return this;
}
- protected class InitScope : Statement
+ public override void Emit (EmitContext ec)
{
- Iterator iterator;
-
- public InitScope (Iterator iterator, Location loc)
- {
- this.iterator = iterator;
- this.loc = loc;
- }
+ //
+ // Load Iterator storey instance
+ //
+ method.Storey.Instance.Emit (ec);
- public override bool Resolve (EmitContext ec)
- {
- return true;
- }
+ //
+ // Initialize iterator PC when it's unitialized
+ //
+ if (IsEnumerable) {
+ ILGenerator ig = ec.ig;
+ ig.Emit (OpCodes.Dup);
+ IntConstant.EmitInt (ig, (int)State.Uninitialized);
- protected override void DoEmit (EmitContext ec)
- {
- iterator.cc.EmitInitScope (ec);
+ FieldInfo field = IteratorHost.PC.FieldBuilder;
+#if GMCS_SOURCE
+ if (Storey.MemberName.IsGeneric)
+ field = TypeBuilder.GetField (Storey.Instance.Type, field);
+#endif
+ ig.Emit (OpCodes.Stfld, field);
}
}
- void Define_Reset ()
+ public override Expression CreateExpressionTree (EmitContext ec)
{
- Method reset = new Method (
- this, TypeManager.system_void_expr, Modifiers.PUBLIC,
- false, new MemberName ("Reset", Location),
- Parameters.EmptyReadOnlyParameters, null);
- AddMethod (reset);
-
- reset.Block = new ToplevelBlock (Location);
- reset.Block = new ToplevelBlock (block, parameters, Location);
- reset.Block.SetHaveAnonymousMethods (Location, move_next_method);
-
- reset.Block.AddStatement (Create_ThrowNotSupported ());
+ throw new NotSupportedException ("ET");
}
- void Define_Dispose ()
+ public static void CreateIterator (IMethodData method, TypeContainer parent, int modifiers)
{
- dispose = new Method (
- this, TypeManager.system_void_expr, Modifiers.PUBLIC,
- false, new MemberName ("Dispose", Location),
- Parameters.EmptyReadOnlyParameters, null);
- AddMethod (dispose);
+ bool is_enumerable;
+ Type iterator_type;
- dispose.Block = new ToplevelBlock (block, parameters, Location);
- dispose.Block.SetHaveAnonymousMethods (Location, move_next_method);
+ Type ret = method.ReturnType;
+ if (ret == null)
+ return;
- dispose.Block.AddStatement (new DisposeMethod (this, Location));
- }
-
- public Type IteratorType {
- get { return iterator_type; }
- }
-
- //
- // This return statement tricks return into not flagging an error for being
- // used in a Yields method
- //
- class NoCheckReturn : Statement {
- public Expression Expr;
-
- public NoCheckReturn (Expression expr, Location l)
- {
- Expr = expr;
- loc = l;
+ if (!CheckType (ret, out iterator_type, out is_enumerable)) {
+ Report.Error (1624, method.Location,
+ "The body of `{0}' cannot be an iterator block " +
+ "because `{1}' is not an iterator interface type",
+ method.GetSignatureForError (),
+ TypeManager.CSharpName (ret));
+ return;
}
- public override bool Resolve (EmitContext ec)
- {
- Expr = Expr.Resolve (ec);
- if (Expr == null)
- return false;
+ Parameters parameters = method.ParameterInfo;
+ for (int i = 0; i < parameters.Count; i++) {
+ Parameter p = parameters [i];
+ Parameter.Modifier mod = p.ModFlags;
+ if ((mod & Parameter.Modifier.ISBYREF) != 0) {
+ Report.Error (1623, p.Location,
+ "Iterators cannot have ref or out parameters");
+ return;
+ }
- ec.CurrentBranching.CurrentUsageVector.Return ();
+ if ((mod & Parameter.Modifier.ARGLIST) != 0) {
+ Report.Error (1636, method.Location,
+ "__arglist is not allowed in parameter list of iterators");
+ return;
+ }
- return true;
+ if (parameters.Types [i].IsPointer) {
+ Report.Error (1637, p.Location,
+ "Iterators cannot have unsafe parameters or " +
+ "yield types");
+ return;
+ }
}
- protected override void DoEmit (EmitContext ec)
- {
- Expr.Emit (ec);
- ec.ig.Emit (OpCodes.Ret);
+ if ((modifiers & Modifiers.UNSAFE) != 0) {
+ Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
+ return;
}
+
+ Iterator iter = new Iterator (method, parent, iterator_type, is_enumerable);
+ iter.Storey.DefineType ();
}
- bool CheckType ()
+ static bool CheckType (Type ret, out Type original_iterator_type, out bool is_enumerable)
{
- Type ret = orig_method.ReturnType;
+ original_iterator_type = null;
+ is_enumerable = false;
if (ret == TypeManager.ienumerable_type) {
- iterator_type = TypeManager.object_type;
+ original_iterator_type = TypeManager.object_type;
is_enumerable = true;
return true;
}
if (ret == TypeManager.ienumerator_type) {
- iterator_type = TypeManager.object_type;
+ original_iterator_type = TypeManager.object_type;
+ is_enumerable = false;
+ return true;
+ }
+
+ if (!TypeManager.IsGenericType (ret))
+ return false;
+
+ Type[] args = TypeManager.GetTypeArguments (ret);
+ if (args.Length != 1)
+ return false;
+
+ Type gt = TypeManager.DropGenericTypeArguments (ret);
+ if (gt == TypeManager.generic_ienumerable_type) {
+ original_iterator_type = args [0];
+ is_enumerable = true;
+ return true;
+ }
+
+ if (gt == TypeManager.generic_ienumerator_type) {
+ original_iterator_type = args [0];
is_enumerable = false;
return true;
}