275 points · by steveklabnik · 7y ago · 190 comments
You'd be blown away by Linux Kernel development then. Multiple magnitudes above any measurement of an await syntax bikeshedding. /u/Perceptes puts it best than I ever could in this top voted comment on /r/rust [1]:
"...I personally don't care at all about the await syntax, and have been very unhappy with that bikeshed being such a focus of time and discussion. The real problems I have with the unstable async system are how difficult it is to reason about. Compiler errors are still largely indecipherable. impl Trait didn't really help here. Documentation is still sparse, so I spend a lot of time banging my head against the wall, trying many formulations of my programs to get just the right incantation of futures wrapped in futures wrapped in futures to get things to compile, only to get page-long type mismatch errors that are near impossible to read, and multiple closures/functions deep of nested futures being returned where any of them could be the culprit. I'm also very frustrated by the lack of progress on "abstract types" that are required for using async functions (and returning impl Trait) from trait methods. Traits are the cornerstone of Rust's type system and yet I haven't seen any activity on this for months. And now we're talking stabilization with this glaring hole. Async streams are another thing I've seen almost no progress on, aside from a blog post from withoutboats on how to deal with the ? operator within async for loops..."
This was 2 months ago, mind you. [1] https://www.reddit.com/r/rust/comments/awa3t1/baby_steps_blo...
I'm just glad that they finally settled on something.
One thing I strongly disagree with - - this article said other notations would require Rust users having to learn more notation. This still requires learning more notation, just it's easy to not even be aware it exists and think a struct had a member called await instead...
That said, I think a postfixing sigil would have been much better. It seems an important enough thing to denote that a bit of special syntax is called for, and the more unique the better.
var value = (await (await startRequest()).GetBody()).Root;
While the Rust syntax would make this a little more clear, I do not think it is a dealbreaker. var value = startRequest().await.getBody().await.Root; var temp1 = await StartRequest();
var temp2 = await temp1.GetBody();
var value = temp2.Root;
which is instantly grokked.They can still introduce a sigil later, if the .await syntax turns out to be common enough in code that the long keyword hinders readability. This is how it was done with the try!(...) feature, which now uses ? as a sigil. But as the article points out, pure sigils are a scarce resource so .await might well be the best way to go anyway.
I don't think this is necessarily a bad choice overall but I find this particular line of reasoning a bit specious.
(Analogies here suck. Instead, consider that the vast majority of programmers read code that has been syntax highlighted. To completely discount that experience at all would be odd.)
EDIT: nvm. it says in TFA not the linked writeup
instead of (await doSomething()).somethingElse()
doSomething()@await.somethingElse()
`foo.await!()` would just expand to `(await foo())`, and anyone could write their own `my_await!` macro that works similarly.
The dot await syntax might hide an await within an expression, as "just another method". You'll need to hunt it down.
I feel await has costs and consequences that need to be explicit. The dot syntax does the opposite, and therefore I feel Rust might be making a mistake of a lifetime (pun intended) on this one.
Not quite; Rust is an expression-favoring language, so `if`, `match`, and even the `loop` keyword can all appear deep within expressions (the first two do so somewhat commonly; the latter is comparatively rare). In addition, the error-handling operator `?` is also used within expressions. (And while we're on the topic, let's remember that even C, a statement-heavy language, also has `?` as a control-flow operator that is not in statement position.)
What's a simple example of the new syntax?
pub async fn do_stuff() {
// ...
}
// elsewhere, inside a fn
// as svnpenn points out
let result = do_stuff().await;https://developer.mozilla.org/Web/JavaScript/Reference/Opera...
chucksmash was concisely showing the syntax for an async function and how you can call it with await.
Note "async fn main" on line 15, and the ".await"s on 21 and 24.
Now, if you read my other comment about executors, this is using a crate called "runtime", which handles submitting it for you, see the `#[]` bit on line 14. Regardless, the syntax would look like this even without this crate; it just removes some boilerplate around the executor and submitting your future to it.
use hyper::Client;
let client = Client::new();
let resp = client.get(url).await;(It's certainly desirable for performance and compatibility to avoid making all subroutines into coroutines, so I understand why most languages have done this.)
And restricting it to the case where coroutines have a single return...
Subroutines are naturally coroutines that don't yield. And it seems like the question of whether it's a subroutine or a coroutine shouldn't be something the programmer needs to worry about.
What I've seen in coroutine libraries is the main reason we need await seems to be for cases when we don't want to await a result.
If you need an unawaited invocation to pass to a routine like gather, you do this:
my_results = await gather(run_job(x) for x in work)
But, even if we can't infer from the type of gather that it must accept a future, a function can have a method that asks it to return a future: my_results = gather(run_job.future(x) for x in work)
You'd often want to dispense with gather. If I have these statements: alpha = run_alpha()
beta = run_beta()
gamma = run_gamma()
return alpha + beta + gamma
In most cases, e.g. if these were requests going over the network, we'd prefer to schedule all three at once. If we want to sequence side-effects, then explicit await makes sense: alpha = run_alpha.await()
beta = run_beta.await()
gamma = run_gamma.await()
return alpha + beta + gamma
That makes the most concurrent option easiest, as opposed to the clunky idiom of "gathering" many results.Futures / async-await is an idiom that makes async code easier to reason about, not something that provides any new theoretical foundation or any functionality that wasn't possible before. Like a type system, it's strictly for safety & convenience.
Whether & where you wait on any individual async request is largely separate from the await syntax. If you can start 3 async requests in parallel, and await on the group rather than each request, you probably should.
That said, the idiom of gathering results sequentially is guaranteed to work and be safe, where hidden dependencies and hard to identify race conditions have plagued attempts to make parallel async code since the beginning of time. The syntax of futures in various languages is making async and parallel code easier and safer for most programmers to use without landing in quicksand.
So, this is true in GC'd languages, but if you see my link below, in Rust, async/await does let you write code that was previously impossible. This is because the compiler can't understand lifetimes in the way that the code is written with raw futures.
In theory, someday, if and when generators are stabilized, this will be true again, but instead with the caveat of "async/await doesn't give you any new thing that wasn't possible before, except that it can do it with safe code, rather than unsafe code."
What we have now with await does change the game, it makes async code appear synchronous, and the advantages of that change should not be underestimated. I think futures & await are huge and positive changes for every language they're showing up in, and they do allow for new kinds of programming, I'm just answering the parent comment's question about whether they're strictly necessary in theory. The answer is that they're not.
And yeah, that's sort of how it works under the covers :)
async fn foo() {
let result = blocking_req(); // awaiting immediately here.
async {
let future = blocking_req(); // not awaited.
// can do more complex stuff w/ the future
}
}
IDK what happened to it, and it is a bit more complex IMO than what the Rust folks went with. However, I don't think it helps your gather case.For gather, I think the problem w/ your proposed
return alpha + beta + gamma
is when does that happen? If I do let some = alpha + beta;
// < ... code ... >
let more = some + gamma;
what happens / when are things evaluated?At any rate, with the syntax as it is, I think your gather example is essentially¹:
alpha.join3(beta, gamma).await
or Future::join3(alpha, beta, gamma).await
(Perhaps minus the `.await`, depending on when you need/want the result.)There's no operator overloading, which I'm fine w/, as there is a need to choose between, e.g., select or join.
¹but I'm new w/ the async stuff, so if I'm wrong I'm assuming that Cunningham's Law will kick in and someone will correct me.
One of the goals behind it was to align async control flow with sync/thread-based control flow, to make it more intuitively obvious when things would run concurrently and when they would not. That is, calling a function, even if async, would immediately run it to completion, while wrapping it up in a closure or async block that gets spawned would run it concurrently.
This is especially relevant to Rust, which departs from other implementations of async/await in that merely constructing a future is insufficient to start it running, which is why you need that `join3` call to explicitly introduce concurrency.
Under the "implicit await" proposal, your first example would look like this:
async fn foo() {
let result = blocking_req(); // await immediately
let future = async { blocking_req() }; // think of async{} like a lambda function
// can do more complex stuff with the future, like:
// future.await()
// Future::join(future, other_future)
// tokio::spawn(future)
}
The thread-based equivalent looks very similar: fn foo() {
let result = blocking_req(); // block the current thread immediately
let closure = || { blocking_req() }; // don't run this yet
// can do more complex stuff with the closure, like:
// closure()
// rayon::join(closure, other_closure)
// thread::spawn(closure)
}I think with the `return alpha + beta + gamma` the idea is that within a scope, everything is done as late as possible, but you can't leave a scope without all results.
Thus, if the code is expanded as:
alpha = run_a()
beta = run_b()
gamma = run_c()
a_plus_b = plus(alpha, beta)
sum = plus(a_plus_b, gamma)
return sum
In that case, the compiler has to determine a partial ordering: a_plus_b <- run_a, run_b
sum <- a_plus_b, run_c
Thus it can generate: await gather(run_a, run_b, run_c)
await plus(alpha, beta)
await plus(a_plus_b, gamma)
And presumably you can detect pure subroutine / primitive invocations.And there would be other hard points where tasks must be fully awaited; e.g. loops wouldn't be able to leak tasks.
Specifically, the problem is that making the decision happen requires refactoring and that can make a small change into a big one. My contention is that for some languages (probably not Rust) it would be beneficial if this didn't impact the code structure heavily.
I've seen smart people simply avoid trying to use asynchronous code in Javascript because it "poisons" the whole stack. Part of this was because it was based on promises, and it meant going through a bunch of logic and refactoring. Arguing against my case, that did result in a slightly nicer structure overall.
Hopefully having proper async / await notation avoids 99% of that mess in Rust by making it a matter of decorating code with the appropriate keywords and being a bit more thoughtful about structure.
And you're obviously right that Rust needs to have sane performance characteristics, let alone being able to export C compatible bindings.
Also if you use multiple modules with their own executors, they don't compose well. You can easily get oversubscription of CPUs.
Javascript's promises are self starting, which I would say is an improvement but the total lack of back pressure is anywhere from galling to highly problematic depending on the problem domain.
Goldilocks solution might be to have default executor behavior with an obvious and straightforward way to override it.
In .NET it defaults to scheduling continuations in the "main" thread as much as possible, with the easiest escape valve being Task<T>.ConfigureAwait(false) that tells it that it can finish continuations wherever they land in the ThreadPool. This is why you can often find a lot of (partly mistaken) advice in .NET to always use ConfigureAwait(false) for "performance" which as often as not leads to people rediscovering the hard way why the easy default is continuations on Main/UI threads. There actually is a more complex TaskScheduler mechanism underlying that big ugly valve, but TaskScheduler is not quite as featureful or easy to control as the RX-equivalent scheduler.
(I heard some rumblings that the .NET team was considering in the long run to better unify async/await TaskScheduler scheduling with the Scheduler model of RX.NET, but I don't know if anything has progressed yet along those lines.)
Python mostly requires manual management of event loops for async/await coroutine scheduling. Most Python code, even/especially using async/await is still generally single-threaded (due to artifacts like the GIL [Global Interpreter Lock] that are getting better with each passing version of Python), so more complicated scheduling is both generally not necessary and also left as an exercise to the user.
ECMAScript 2017 (JavaScript) async/await is also mostly running in single threaded event loops (though not manually managed like Python; generally browser UI event loop managed).
https://medium.com/bynder-tech/c-why-you-should-use-configur...
If you're writing a console application, the main thread doesn't have one. When an async function wants to resume, it will usually resume on some thread pool's thread. Potentially different one each time. Can be any other thread too, the runtime just resumes running the function on the same thread which completed the await.
But if you're writing a GUI app and launching an async function from its GUI thread, that thread has a current sync.context. When the function will want to resume running or fails, the runtime will resume/raise exception on the same thread where it started. More precisely, the runtime delegates the decision to the sync.context, and the contexts set by GUI frameworks choose to resume on the GUI thread.
This may cause some funny deadlock bugs, but in most cases works surprisingly well in practice.
Also it's easy to implement custom synchronization contexts if needed.
(I use and love fish shell for many years now; thank you.)
Is this syntax for native coroutines? Can it be combined with existing user and stdlib syntax? What pathways for syntax development does this decision cut off entirely, and pathways does it leave open? What did the Rust community / maintainers learn from this debate, and how can the Rust community avoid such battles in the future?
Due to the connotations of "religious battle", it's hard to get a good answer here. Nobody wants to be painted in this light.
> Is this syntax for native coroutines?
No.
> Can it be combined with existing user and stdlib syntax?
Yes.
> What pathways for syntax development does this decision cut off entirely, and pathways does it leave open?
Nothing outside of the async/await feature itself.
> What did the Rust community / maintainers learn from this debate, and how can the Rust community avoid such battles in the future?
This is too long for an HN comment :)
Haven't we all found ourselves lined up as one of a pair of camps over some heated dispute over a bit of minutiae? The whole time you know it's a bit silly, but not entirely and you feel compelled to continue to argue.
Using a term like "religious battles" with tongue firmly in cheek is recognizing that we're prone to such things because we're human beings, by putting a lampshade on it.
My impression of async/await is that it’s one part of making concurrency grokkable, and I’m not sure whether the debate was taking all that into account: https://vorpus.org/blog/some-thoughts-on-asynchronous-api-de...
Not at all!
> My definition of religious war is butting heads about problems that don’t have a clear right answer (tabs/spaces).
So this is where we get into the meat of it. I personally do believe that a lot of the discussion was around things that don't have a clear right answer. But (and the post mentions this a bit), that doesn't mean that it's inherently religious, it means that different people value different aspects of the solution differently. The big difference between this discussion and the tabs/spaces discussion is that each person can make their own call with tabs and spaces, but this syntax affects every user of Rust. That means we can't just say "well this is a religious debate, do whatever" because then the feature does not exist.
> If there are new things considered by the community that make the discussion worthwhile then it’s absolutely worth having; but if it causes people to burn out on the community down the line then maybe more moderation would be helpful.
Yes, it is a fine line. There's a lot to it, but it is something that people are thinking about, for sure.
> I’m not sure whether the debate was taking all that into account
I can assure you that the overall development of the feature took every possible thing into account. Part of the reason that this was so synatx focused is that the team spent multiple years working on the semantics. The syntax was all that was left.
I am not 100% sure what you mean with the blog post link, as I'm not really a Python person, so I can't quite grok what you're talking about, exactly. If you can elaborate a bit I can too!
That's a different question than "where does the await go" and it was certainly taken into account.
Why does it take so long for swift to have this? Swift + iOS developers really really benefit from it. And there are loads of ios developers compared to rust developers.
Not too dissimilar for JavaScript's async/await syntax which needed support for Promises and Generators as progress points.
Really looking forward to this once it reaches down into some of the network/web frameworks, database drivers etc.
Eagerly waiting for the 1.37 release!
Great job Rust Team!
https://paper.dropbox.com/doc/Await-Syntax-Write-Up-t9NlOSeI...
Main points against:
1. Interacts poorly with the ? operator for propagating errors. You'd need to do (await foo())?
2. Chains poorly. `await foo().bar().baz()`
- a. What are you awaiting? foo() or foo().bar().baz()
- b. What if you wanted to await foo().bar()? (await foo().bar()).baz() is messy.
- c. What if you wanted to chain promises? Like httpRequest.send().body() . In many libraries such as Python's requests, the first returns a future for a response with headers and only a later call waits until the body is returned. `await (await httpRequest.send()).body()`
Why not .await() or .await!():
You can read the OP which contains links to more blog posts on the reasoning. I think this is a bad decision precisely because of the questions you're asking. At least making it a 'magic method' (i.e., Future::await(...) or future.await()) with no implementation would have been better in basically every way. A 'dot' operator already exists and this just makes it confusing.
The reason this process took so long, is that most people feel exactly like you do, except that they don't agree about which proposal they hate.
But the rest of the language is really good so don't let this scare you off. Most of rust feels very well thought out and reasonable.
Disappointed we didn't get something like a magic method (e.g., lang item) (which isn't without precedence [1] [2]) so we could have had `Future::await(fut)` or `fut.await()`.
[1] - https://manishearth.github.io/blog/2017/01/10/rust-tidbits-b... [2] - https://manishearth.github.io/blog/2017/01/11/rust-tidbits-w...
You could implement that syntax and still make `await` a keyword, without doing the usual method lookup and without letting no_std libraries change the term, just like `.await`- that's an orthogonal concern.
Compared with `fut.await`...
> There's no hint in that expression that it's anything other than a field access.
At least there is precedence for functions to have magical compiler-ness for 'doing stuff', instead of overloading field access which is one of the simplest operations you can have.
> ... requires knowing the type of `fut` ...
tbh, you don't need to know how await works. It goes and does stuff and returns a value. If you need to know what it does, you're looking up the types and seeing, 'oh its a future' and looking at that.
Contrast with the field access one and you don't even know its something else entirely.
I guess I just don't buy that it can't be a method. Like, formally, yea, it isn't a well-defined, safe Rust method. But make the impl
fn await(self: Self) -> Self::Target {
intrinsic::await(self)
}
Now its a method defined on the `Future` trait, it's discoverable, it's clearly magic, it's ergonomic... In my opinion, it beats the field access one in every conceivable metric.It's just frustrating, I guess.
Except we don't actually have precedence for "I'm going to declare a function, but it's not actually implemented in Rust, instead it's a cue to the compiler to do other magical stuff". Lang items are in fact the opposite; they're telling the compiler "here's the implementation for an extension point you've defined". For example the "panic_impl" lang item is a function that's invoked when code panics. The closest I can think of to what you're referring to is the fact that the type identified as "owned_box" has special dereferencing behavior, but that can be modeled as the compiler providing an implementation for an un-namable trait on the owned_box item where the trait represents the new deref behavior (just as how Deref and DerefMut represent the existing deref behaviors).
> tbh, you don't need to know how await works.
You need to know the type in order to determine if `fut.await()` is invoking this magical semantics-altering compiler behavior or if it's just invoking a method that happens to be named `await` (given that the lang_item proposal means await is no longer a keyword).
> Contrast with the field access one and you don't even know its something else entirely.
Except you do, because await is a keyword. It's impossible in Rust 2018 to have a field named await, and so any expression that looks like `x.await` is guaranteed to be an invocation of the await behavior.
> I guess I just don't buy that it can't be a method.
It cannot be a method that is implemented as a call to an intrinsic. The await keyword requires rewriting the function that invokes it.
> That won’t be the end of the async/await feature - there will be a lot of extensions left out of the minimum feature
Is there a summary of these somewhere for perusal?
Worth noting that in this case the discussion over semantics has been ongoing and nonstop since around 2013, since it's such a big feature that it took a lot of trial and experimentation to figure out, and only then after being broken up into several large sub-tasks which all had to be individually discussed as well; see the epic comment thread on the Pin stabilization tracking issue as an example of just one semantic discussion towards this end: https://github.com/rust-lang/rust/issues/49150
half_square = divide(square(a), 2)
In comparison to: half_square = a.square().divide(2)
Many find the latter much more pleasant to read, and things like this can make a big difference in how fun I find it to use a language.I don't think either is better but one is definitely familiar.
Generally I try not to care about syntax too much (except putting $ on the front of a variable, that annoys me not so much because they did but because not everyone did so every time I switch from PHP to TypeScript I end up putting $ on at least once a day), the weird part is that I write idiomatic code in both so my brain knows it shifted context but I still put the $.
let $foo = bar;
Just looks wrong.Weirder still when I run into code written by people who do
let $foo = $(foo);
For jQuery stuff (I totally get the reason why).Brains are funny things.
half_square =
a
|> square
|> divide(_, 2) find_half_square = square >>> (flip divide) 2
This creates a function which takes a value, performs `square`, then performs `(flip divide) 2`. It's written in pointfree style, which means the function's input is never written in the definition of the function, which I find to be extremely aesthetically pleasing (as it allows me to focus on the composition of functions, without thinking about passing arguments around). This is one situation where changes in syntax allow you to reason about programs quite differently.In practice, syntax is the UI for a programming language. And just as with any UI, there's a bunch of tradeoffs between how easy the language is to use for a newbie (who knows nothing), how easy it is for casual user (who knows a few core constructs but has to lookup advanced functionality), how productive it is for an expert (who has a vast working memory of functionality), and how powerful it is (in terms of which constructs can even be represented). Different users will have different opinions on which tradeoffs are justified, largely depending on where they fall on this continuum.
On one side of the (practical) continuum, you have languages like COBOL, BASIC, PHP, and Hypercard, which are explicitly designed to seem familiar to people who know other non-programming technologies. On another, you have languages like Scheme, C, Go, and Java, which have a small set of broadly-applicable core concepts but require some verboseness to express lots of common patterns. And on the third, you have languages like C++ and Perl where experts can express very powerful programs without a whole lot of typing, but which can be rather impenetrable to people who haven't spent years mastering them.
Why is optimizing for your tastes the correct thing to optimize for?
Syntax very obviously matters.
Besides, futures are very old in Rust at this point (relative to the language's age) and had been discussed years ago. The reason people aren't seeing those discussions is because they happened a long time ago but syntax happened a month ago.
I think this also highlights the pitfalls of being community-centric. If Rust were run more like chromium or something, this sort of thing just ceases to be an issue. Major kudos to the Rust team for managing it really well.
(I'm not arguing that they weren't bikeshedding...)
Also, there is a notable usability difference, wrt reading the flow of lines, chaining and parentheses. Learnabilty/wierdness was a syntax consideration, but not the only one.
0. Though some would argue that making them completely orthogonal to the point where the user can't tell the difference is a horrible design decision.
Alternatively, the syntax in Haskell just lends itself to lazy evaluation, and requires explicit annotation syntax to be strict. Contrasted with Python, which has a syntax that makes strict evaluation an easier default to express.
If all languages can express, with some effort, the same exact semantics as any other language, then the only difference is syntax.