-
Notifications
You must be signed in to change notification settings - Fork 48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Yield closures #49
Comments
This issue is not meant to be used for technical discussion. There is a Zulip stream for that. Use this issue to leave procedural comments, such as volunteering to review, indicating that you second the proposal (or third, etc), or raising a concern that you would like to be addressed. |
I have a concern that changing the closure argument variables after each let my_generator = |arg1: i64| {
// can get initial resume arg by instead starting
// with something like (syntax up for bikeshedding):
// |arg1: i64| initial_resume: &'static str = yield {
//
dbg!(&arg1);
let yielded1 = 123;
// key part of concern:
// yields yielded1 to caller, gets resume_arg back,
// does *NOT* modify arg1 since arg1 wasn't mentioned
let resume_arg: &'static str = yield yielded1;
dbg!(&arg1); // always prints same thing as previous dbg!
123.45f64
};
// exact generator type up for debate
let _: Fn(i64) -> (FnPin(&'static str) -> YieldOrReturn<i32, f64>) = my_generator; |
@programmerjake I get it. I was in the yield-expression camp for a long time too. But trust me, assign-on-yield really is the better option! I'll list a few reasons here but if anyone is unconvinced, they should drop by Zulip and duke it out with me there.
|items| {
for _ in items {
yield;
}
} This will error out with something like:
So even if a user totally misunderstands the behavior of
|mut is_opponent_near, mut my_health| loop {
// Find opponent
while !is_opponent_near {
let state = yield Wander;
is_opponent_near = state.0;
my_health = state.1;
}
// Do battle!
let mut min_health = my_health;
... |
Discussed in the rust-lang meeting. There is some amount of excitement and enthusiasm for taking this approach eventually, however we feel like we don't presently have the design bandwidth to oversee a project of this kind, so we're going to put this into final comment period with disposition close. We do expect at some point in the future to be talking about the ability to have built-in syntax for iterators or streams, and it would make sense to revisit this discussion at that time. To that end, one thing that would really be appreciated is if someone wanted to try and capture the state of the design discussion here, including unknowns and challenges. We could put it under the lang-team.rust-lang.org website "design notes" section. |
Placing in final comment period and we'll revisit next triage meeting. |
Sounds good! Thanks for hearing me out.
I'll go ahead and put something comprehensive together in the next week when I have some free time. |
#52 is up. |
Closing this issue. People should review #52 asynchronously, and we can talk about it for a future roadmap item. |
Proposal
Summary and problem statement
Rust has the ability to yield and resume function calls by transforming functions into a state machines. However, this ability is currently available to users in a very limited fashion (async blocks, functions) because of the complex design choices required in generalizing the capability. I believe that we have now found a very simple version of "stackless coroutines" which will resolve this.
In short, ordinary closures should be allowed to
yield
in addition toreturn
. For example, to skip alternate elements of an iterator:As expected, arguments can be moved by the closure at any point. If an argument is not moved prior to
yield
orreturn
, it will be dropped. When the closures is resumed after eitheryield
orreturn
, all arguments are reassigned:From the outside yield closures work the same as non-yield closures: they implement any applicable
Fn*
traits. Since a yield-closure must at least mutate a discriminant within the closure state, it would not implementFn
. Yield closures which require stack-pinning would additionally be!FnMut
, instead implementing a newFnPin
trait. Note that allFnMut + Unpin
should also implementFnPin
.Motivation, use-cases, and solution sketches
Yield closures would act as the fundamental "coroutine" in the Rust language which in-language sugars and user-defined macros could use to build futures, iterators, streams, sinks, etc. However, those abstractions should not be the focus of this proposal. Yield closures should be justified as a language feature based on its own merits. To that end, below are some example use-cases.
Since yield closures are simply functions, they can be used with existing combinators. Here a closure is used with a char iterator to decode string escapes:
Here is a similar pushdown parser utility which assists in base64 decoding:
Since yield closures are a very consise way of writing state-machines, they could be very useful to describe agent behavior in games and simulations:
And of course, yield closures make it easy to write all kinds of async primatives which are difficult to describe with async/await. Here is a async reader → byte stream combinator:
Once closures
Some closures consume captured data and thus can not be restarted. Currently such closures avoid restart by exclusively implementing
FnOnce
. However, aFnOnce
-only yield closure is useless even if unrestartable, since it still might be resumed an arbitrary number of times. Thankfully, there is a different way to prevent restart: a closure could enter a "poisoned" state after returning or panicking. This behavior is generally undesirable for non-yield closures but could be switched-on when needed. I recommend amut
modifier for this purpose since it is A. syntactically unambiguous and B. invokes the idea that aFnMut
implementation is being requested:Alternatively, all yield closures could be poisoned by default and opt-out with
loop
:Poisoned-by-default is closer to the current behavior of generators but breaks the consistency between yield and non-yield closures. I believe the better consistency of the
mut
modifier will make the behavior of yield dumber and less surprising. However, that trade-off should be discussed further.GeneratorState-wrapping
A
try { }
block produces aResult
by wrapping outputs inOk/Err
. Anasync { }
block produces aFuture
by wrapping outputs inPending/Ready
. Similarly aiterator! { }
block could produce anIterator
by wrapping outputs inSome/None
and astream! { }
block could produce aStream
by wrapping outputs inPending/Ready(Some)/Ready(None)
.However, there is a common pattern here. Users often want to discriminate values output by
yield
(Pending
,Some
, etc) from values output byreturn
(Ready
,None
, etc). Because of this, it may make sense to have all yield-closures automatically wrap values in aGeneratorState
enum in the same way as the existing, unstable generator syntax.Although this should be discussed, I believe that enum-wrapping is a separate concern better served by higher-level try/async/iterator/stream blocks.
Async closures
There is an open question regarding the behavior of async + yield closures. The obvious behavior of such a closure is to produce futures, in the same way that a non-yield async closure produces a future. However, the natural desugaring of
async || { yield ... }
into|| async { yield ... }
doesn't make a whole lot of sense (how should aFuture
yield anything other thanPending
?) and it is not clear if an alternate desugar along the lines of|| yield async { ... }
is even possible.For now I would recommend disallowing such closures since async closures are unstable anyway.
Prioritization
In addition to the general ergonomic wins for all kinds of tasks involving closures, a general way of accessing coroutines allows users a far less frustrating way to implement more complex futures and streams. It will also allow crates like async-stream and propane to implement useful syntax sugars for all kinds of generators or iterators, sinks, streams, etc.
Links and related work
The effort to generalize coroutines has been going on ever since the original coroutines eRFC. This solution is very closely related to Unified coroutines a.k.a. Generator resume arguments (RFC-2781). Further refinement of that proposal with the goal of fully unifying closures and generators can be found under a draft RFC authored by @CAD97.
Initial people involved
What happens now?
This issue is part of the experimental MCP process described in RFC 2936. Once this issue is filed, a Zulip topic will be opened for discussion, and the lang-team will review open MCPs in its weekly triage meetings. You should receive feedback within a week or two.
This issue is not meant to be used for technical discussion. There is a Zulip stream for that. Use this issue to leave procedural comments, such as volunteering to review, indicating that you second the proposal (or third, etc), or raising a concern that you would like to be addressed.
The text was updated successfully, but these errors were encountered: