352 points · by gaogao · 7y ago · 261 comments
My first experience with futures was in the form of QFuture (https://doc.qt.io/qt-5/qfuture.html), and there you call .result() to block and wait for the result. This postfixing is intuitive.
Rust's "?" operator is neat. I don't know if I've seen a postfix operator anywhere else yet. It's certainly possible Rust got this language aspect wrong, but as a user it feels pretty right.
Given the existence of the "?" operator, and the fact that futures resolution via postfix is intuitive (and not a new thing either), IMHO the best course of action probably is postfix. I'm not sure if literally ".await" is the best, but it's in the ballpark.
(1) It looks like a field access, and field accesses are "cheap", method invocations aren't. This breaks the 'conceptual weight' model when you look at a line of code. Field accesses are simple and understood. It becomes impossible to gauge the 'cost' of a line by looking at it unless you're intimately familiar with the workings of 'await' and there's no visual cue.
(2) If we create new such postfix operators in the future we'll have to break yet more source code by reserving yet more field names in all structs in all existing code. This whole postfix thing is proving itself nice to work with so I'd prefer a path of less destruction if we do lean more into it.
(3) It's a one-off that's different from everything else in the language that's being shoehorned into existing syntax.
IMO, it's either break existing syntax by introducing something new or break semantics of existing syntax. I'll always lean towards the former over the latter. I like it being postfix, it's very much in the '?' family of ergonomics which has shown itself quite nice to work with. I'd prefer postfix "@await" or "!await".
This is already the case; all keywords in Rust are reserved keywords, not contextual keywords, so you already can't have a field named, say, `return`, despite the fact that a hypothetical `foo.return` would otherwise be unambiguous. Further, with the Edition system and rustfmt, reserving keywords in this manner shouldn't be disruptive.
> (3) It's a one-off that's different from everything else in the language that's being shoehorned into existing syntax.
The paragraph at the end of the OP suggests that the language team is seeking to propose allowing certain other keywords (specifically those that can return useful values) to be used in postfix position (which implies that `await` could then be used in prefix position as well), which could e.g. (I'm spitballing here) replace the `.for_each()` method on iterators with just `.for`.
Well, the keyword could instead be "@await" instead of "await" meaning that no regressions would be introduced with field names, either now or in the future, right? Unless I'm mistaken, the '@' character isn't a valid prefix for an identifier.
> The paragraph at the end of the OP suggests that the language team is seeking to propose allowing certain other keywords (specifically those that can return useful values) to be used in postfix position (which implies that `await` could then be used in prefix position as well), which could e.g. (I'm spitballing here) replace the `.for_each()` method on iterators with just `.for`.
That's fine, I guess, but then we'd have yet more keywords we can't use. However, "@for" would not break anything. FWIW the way I read that section, the proposal enjoys little support.
There is. Your editor is going to show the await keyword in a different color. (Unless you happen to be Rob Pike.)
You mean like C++'s a.this_method_is_a_function_call(...) did? Not to be confused with a.function_pointer_field(...), despite having literally identical syntax.
Personally, I think they should have intoduced a dot-keyword instead of postfix ?; it's too easy to miss, especially for something that hides a implicit return.
Lua[1], C++/Boost[2] also use "yield" it's not that uncommon and there is nothing new.
[1] https://www.lua.org/pil/9.1.html
[2] https://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/ov...
I wrote a lot of async/await code in C#, where it's a prefix operator, and I think what they did makes more sense. C# syntax works great when all you're doing is awaiting on a single call per line, but as soon as you start doing e.g. method chaining, you have to put parentheses everywhere, and it gets real messy real fast. This looks cleaner.
I'd _much_ rather use something like `?` than `.await`, though. Using a keyword just feels wrong in a few different ways.
I feel like the committee has worried about the wrong things when considering postfix vs prefix. Their main concern seemed to have been the extra syntax required to make prefix work with . And ? (i.e., (await foo).bar() ), but while avoiding this makes for a more optimized language I'm concerned they've missed the impact this will have on new people.
Or maybe I'm just a Luddite :)
I think that's a great reason to evaluate new syntax/features on how they will be used, as opposed to how they will attract (or not) new users. New users are already going to be expecting things to be different, and so making this one thing more familiar probably won't make much difference. On the other hand, code lives for a very long time once it's been written, so making the right choice in terms of readability/maintainability seems like the right move.
I read this post and thought 'async as a prefix is intuitive!', but that's only because I saw it first in C#.
Rust already has an immense learning curve despite its ergonomics, I say it should continue to experiment. Same way Haskell does.
I do wonder if `.await` could have a sigil equivalent the same way `try!` did with `?`. `…` could work if it's not already used as spread args.
It doesn't take too long to pick up and become comfortable with a new syntax in a programming language.
Imo, the reason some esoteric languages fail are not purely because their syntax is obscure but because even once you learn the syntax, it is still hard to understand the code (example: Brainfuck).
With Rust, once you learn the new syntax, you can understand Rust code with relatively little effort.
EDIT: this might very well be the case here though, especially future extension for similar operators and chain-ability.
Some folks came up with the idea of a "weirdness" budget - arguing that Rust had come close to using it all up.
>I feel like the committee has worried about the wrong things
There is no "committee" really, and all the worries have been expressed and weighed. The debate over this syntax has been going on for months and had huge community involvement.
It's all been summed up in this document:
https://paper.dropbox.com/doc/Await-Syntax-Write-Up--AcIbhZ1...
I was definitely in the prefix camp before I read that document.
I don't really see how they refute this argument though? Clearly they state arguments both in favor of postfix and prefix but it feels like some framework for weighing the arguments is missing, otherwise it just comes down to how individuals weigh the arguments.
Boats' keynote at rust-latam goes into some more detail as well.
https://www.youtube.com/watch?v=skos4B5x7qE
I'm just a casual observer here, but it seems like just about every argument and position on the subject has been iterated across Github, internals.rust-lang.org, the IRC/Discourse/Zulip chats, Reddit, and now HN.
This post by boats is just the next stepping stone alerting the community to the direction the team is leading and that it's going to be over soon.
Every time I see a statement like this, I remember a (paraphrased) statement from Rich Hickey: "[musical] instruments are made for people who can play them!".
I think unless you are specifically designing a beginner language (like Scratch), you should not take into consideration "ease of use" or "familiarity" arguments.
Familiarity is a big part of that, although ease of use is bigger (which is probably why python got the traction it did despite being unfamiliar to people who came from braces-land).
If I got to choose between the Clojure I know today VS a Clojure designed for ease of use and being familiar, I'm pretty sure I would chose the first.
Just like APL is much better for some tasks compared to Python, and vice versa.
Years later, it was used at IBM to describe what the IBM 360 computer would do. After that, it got turned into APL\360 around 1962 (i.e there weren't all that many programming languages to be familiar with, then). The book "APL\360 An Interactive Guide" by L. Gilman, 1970, has a foreword which says:
APL is clearly gaining acceptance at this time as a computer programming language. This acceptance is not hard to understand. APL is one of the most concise, consistent, and powerful programming languages ever devised. (UX is important!)
and
From a pedagogical standpoint APL has a number of advantages. The material can be taught and used in small pieces. A student can be trying his hand on simple operations after five minutes of instruction. What he doesn't know won't hurt him (a statement that cannot be made about most other languages). If he tries something illegal such as division by zero or adding a number and a letter, he gets an understandable error message and is free to try something else. Nothing the user can do will cause the system to crash. (Usability!)
and
It is indubitably true that a "clever" programmer can use these advanced operators in such a way as to produce an "opaque" program, that is, one so compact and concise as to be nearly impossible for anyone else to understand. Whatever else may be said about such programs, which are questionable in many contexts anyway, they should not be used in demonstrations of APL. Experienced programmers who have seen APL demonstrated in terms of the fantastic cleverness angle sometimes criticize the language as being hard to understand, when their criticism more properly should have been directed at the demonstrator. Such misplaced cleverness is not to be found in this book. All operators are thoroughly covered, but there is no attempt to show off the ingenuity of the authors in writing ingeniously condensed programs.
Thinking that "ease of use" should not be considered because [favourite reasons] is probably the number one misunderstanding software engineers have about humans. :) Please read Norman's "The design of everyday things", before accidentally making the life of someone miserable through software.
Which musical instruments are _not_ weird?
And yet, for the most part, trumpets have the same valve configurations, pianos are in the same key, and violins have the same string arrangement.
Unlike different musical instruments, all programming languages make the same sound (more or less). The goal of using a programming language is not to use that programming language, but to program a computer.
> you should not take into consideration "ease of use" or "familiarity" arguments.
Especially if you really don't want it to be wildly successful.
It's not a binary choice for the most part.
- Ease of use will not be promoted over long term growth or power (I.e., the instrument should be designed such that it can ideally facilitate indefinite growth of skill. It shouldn't be a toy that only works up to a certain point.)
- Very often, ease of use can be optimised in such a way that it does not conflict with the first point, rendering the entire discussion moot.
- Familiarity is a non-goal unless the familiar design has the same properties as the optimal design, with regards to the first point.
This is not to say that easier, beginner friendly designs that _does_ sacrifice the long term power or growth aren't valuable. It's a different design goal, though.
I also wouldn't use a programming language that is optimized for increasing the number of users at the expense of performance, clarity, stability, consistency, or power. I don't want a language that appeals to most people, I want one that disproportionately appeals to careful and competent people.
"what makes _me_ sad is the focus on "most folks" and "Joe Sixpack".
why are we even _thinking_ about home computer equipment when we wish to attract professional programmers?
in _every_ field I know, the difference between the professional and the mass market is so large that Joe Blow wouldn't believe the two could coexist. more often than not, you can't even get the professional quality unless you sign a major agreement with the vendor -- such is the investment on both sides of the table. the commitment for over-the-counter sales to some anonymous customer is _negligible_. consumers are protected by laws because of this, while professionals are protected by signed agreements they are expected to understand. the software industry should surely be no different. (except, of course, that software consumers are denied every consumer right they have had recognized in any other field.)
Microsoft and its ilk has done a marvelous job at marketing their software in the mass market so that non-professional programmers pick them up and non-programmers who decide where the money should be wasted will get a warm fuzzy feeling from certain brand names. I mean, they _must_ recognize that nothing else they buy for their company is advertised in the newspapers that morning and they aren't swayed by consumer ads when they buy office or plant equipment, are they? so _why_ do they swallow this nonsense from the mass-marketing guys hook, line, and sinker?
they don't make poles long enough for me want to touch Microsoft products, and I don't want any mass-marketed game-playing device or Windows appliance _near_ my desk or on my network. this is my _workbench_, dammit, it's not a pretty box to impress people with graphics and sounds. when I work at this system up to 12 hours a day, I'm profoundly uninterested in what user interface a novice user would prefer.
I'm reminded of the response to how people of little or no imagination were complaining about science fiction and incredibly expensive space programs: "the meek can _have_ the earth -- we have other plans".
no, this is not elitist, like some would like to believe in order to avoid thinking about the issues. this is just calling attention to the line between amateurs and professionals, between consumers and producers, that is already there in _every_ field. I want people to wake up to this difference and _reject_ the consumer ads when they look for professional tools. if it's marketed to tens of millions of people, it is _not_ for the professional programmer, and not for you. if its main selling point is novice-friendliness, ignore it unless you _are_ a novice. (and if you are a novice trying to sell your services in a professional market, get the hell out of the way.)
https://groups.google.com/forum/#!topic/comp.lang.lisp/HCMKe...
The most scary thing that threw me off the most were lifetimes (which for beginners sake are gladly not needed all that often).
I have trust in the Rust developers and the community that they will choose something very well thought out, because for now the whole language feels incredibly well considered.
I agree that it looks strange at first. But I think I'll get used to it.
Also is it just me or the switch pattern really is inspired by Rust match?
- this is a lot easier to chain, which is very useful, and
- the "future expansion" might bring a prefix await anyway (although introducing two syntaxes for the same thing might be even worse).
I'd prefer "f await" to "f.await" because it feels a lot less magical and lets me stick to my intuition that "." is just for stuff implemented by the library, but maybe that's just me.
Kotlin uses `.await()`.
I'll be pretty intrigued to see what they come up with for that. I've been up closer to the Go developer's attempt to connect with the community, and while I'm not going to say they've done everything perfectly on their end, I've also been sort of frustrated by the way that they'll put up a request for comments about something in particular, and a good chunk of the community replies basically throw away everything they're talking about and rewrite arbitrary amounts of the language from scratch. By "everything", I don't just mean the direct proposal under discussion, but the goals of the proposal, the discussion of alternatives from other languages and how they are and are not relevant, as alluded to above the things already proposed and rejected for solid reasons, the context around the runtime and how it interacts with that... that is, not just the proposal itself, but all the thought and reasoning around it too. That wasn't really the question, so to speak. This frustrates everyone, on all sides, in various ways.
A lot of the problem is structural to what is being done; there's a lot of impedance mismatch between the core designers and the community at large for any language. It would be interesting to see some explicit thought around how to address that, from a community with Rust's experiences.
For example, some users might desire major redesigns of past work but not bear the cost of the rework. As such, they might perceive some small improvement without any (direct) cost.
Personally, I think some groups have moved so far in the direction of community involvement that they forget the practical implications of diversity. Leadership is hard for many reasons — one big reason is that leading sometimes means making some people unhappy. Still, this is much better than inaction.
That's a non sequitur. Trust is not mandated by company boundaries. I for one trust in the competence of the Go maintainers, while at the same time having absolutely zero trust in Google as a company.
That's fine. But ultimately Go employees do not work for you and cannot put much effort into proving they are good at solving problems for you, since the company doesn't pay them to do it. There will not be a track record in users eyes of their design decisions and not much trust from users they are even capable of doing it well.
I don't think that can explain the observations I've made. Either that or the sort of trust you describe is simply impossible, because I've never seen it in any language community I've been in.
I'd lean more towards a lack of clear description to the community for what they're looking for, and the community buying in enough that when communicating amoungst themselves they also do some lightweight enforcement of the expectations.
No one argues about the syntax, because everybody "wins" and gets their own syntax as a result, which is often held up as a key part of the explanation for why the Lisp family languages are wonderful and fun and mind-expanding and just awesome in every way... yet rarely escape from "niche" status and are yet to even threaten to break into the really top-tier languages.
Because languages like Rust and Go, and Python and Java and honestly almost every other non-Lisp family language, want more cohesion in their codebases, they need a different solution to the problem.
(my-new-syntax-name arbitrary other stuff goes here)
Related to this, some things that would have to be primitives in many other languages can be implemented nicely by anyone as ordinary libraries in Scheme.I like this explanation.
But this whole post could really use some more concrete examples of the at the very least the final style being used in various situations. Not just mainly `expression.await`.
Keep up the work on this, I'm excited to use this in my projects.
foo.bar(..).baz(..).match {
Variant1 => { ... }
Variant2(quux) => { ... }
}> In particular, some members of the language team are excited about a potential future extensions in which some “expression-oriented” keywords (that is, those that evaluate to something other than ! or ()) can all be called in a “method-like” fashion. In this world, the dot await operation would be generalized so that await were a “normal” prefix keyword, but the dot combination applied to several such keywords, most importantly match:
my_iter
.foo()
.bar()
.return
more appealing than return my_iter
.foo()
.bar();
I could see it happening, but I'll definitely need some time to get used to it.I also appreciate that this proposal was insanely bike-shedded and so really, any decision is better than no decision. I would've been happy with "await << f()" if it meant we could get this feature (lots of Rust projects I'm interested in are waiting on async/await before focusing on further development).
let db_conn = await pool.connect()
(Which is what e.g. Python uses, with the downside that you tend to need to parenthize more because await has very low precedence).vs
let db_conn = pool.connect() await
.await is not soo bad, kinda method-y let db_conn = pool.connect().awaithttps://paper.dropbox.com/doc/Await-Syntax-Write-Up--AcIbhZ1...
My main issue with .await is that it does look method-y rather than keyword-y. But while I like Python's "await expr" syntax in Python the existence of ? and chaining of methods in Rust justifies having a different syntax for it.
I don't know enough about rust to understand how this would operate during compile time w.r.t if a user tries to define a field named 'async'. Is that no longer allowed or would the compiler be able to disambiguate?
error[E0721]: `await` is a keyword in the 2018 edition
--> src/lib.rs:2:5
|
2 | await: i32
| ^^^^^ help: you can use a raw identifier to stay compatible: `r#await`
[0] https://play.rust-lang.org/?version=stable&mode=debug&editio...https://en.wikipedia.org/wiki/Reserved_word
> Not all languages have the same numbers of reserved words. For example, Java (and other C derivatives) has a rather sparse complement of reserved words—approximately 50 – whereas COBOL has approximately 400. At the other end of the spectrum, pure Prolog and PL/I have none at all.
I don't really know why modern programming languages bother with reserved words. Yes, it would be confusing to have a variable named 'if', but compared to all of the other ways to write confusing code in, say, C, that's barely a drop in the bucket. Plus, it's something good tooling (highlighting, for example) could obviate, as it's entirely possible to use a grammar to show exactly what role each token is playing in a statement.
Preventing potential footguns prevents a large number of bugs. In fact, preventing a specific kind of footgun is one of the primary reasons that Rust exists.
Fewer footguns means easier to work with code. Easy to work with code means fewer bugs. If having reserved words removes more footguns than it creates than they are a good thing to have - and IMO - they do indeed prevent confusion and footguns.
As long as these footguns can be removed without giving up much in exchange, I say remove all footguns!
I would speculate that both will be true. The compile could disambiguate, but it will not be allowed.
I just finished overhauling a rather involved Tokio/Future based project, and having await/async in the language spec will be a big step forward (and I'm hoping the compiler errors improve as well).
As always, kudos to the Rust team for making decisions that are well-reasoned and documented and in a way that looks to the future of the language (and not just meeting a feature deadline)!
Pun intended?
This syntax makes it clear that’s it’s not a function or macro invocation, works the same way as ‘?’, and allows for clear and concise chaining.
"This is the best proposal, except the syntax doesn't make sense, we don't know if we can implement it, and conversation has broken down to the point where we are running in circles and we don't expect to have any more ideas."
I am curious what the current way to do non-blocking code in Rust is and why it's so bad that they'd introduce this much confusion to the language design to fix it.
By the way, the idea you mention may also be true for democracy: the quote goes something like “Democracy is the worst form of government except for all the others.”
If you have a design option that has not already been considered, I’m all ears.
It raises my esteem of the Rust lang leadership that they eventually realized what they had to do and picked something.
(Also would love your take on the question in the last line of my comment. My gut as an outsider is that the best solution may be cultural not technical, except Rust is struggling to implement cultural projects now that the community is scaling fast. But you know what I don't.)
Problems with differentiating .await from .member can easily be solved by using syntax highlighting. Also, Rust is already strange to write, this is just one more quirk one will get used to.
There were two main objections:
First, a Rust async function like this (using explicit lifetime annotations for exposition purposes only, normally they would be elided)...
async fn f<'a>(r: &'a i32) -> i32 { ... *r ... }
...desugars to a sync function whose return value closes over its arguments: fn f<'a>(r: &'a i32) -> impl Future<Output = i32> + 'a { ... }
Sometimes you want the future to live longer than the arguments, so you write that desguaring yourself: fn f<'a>(r: &'a i32) -> impl Future<Output = i32> {
let i = *r; // Deal with the reference *now* before constructing the future.
async { ... i ... }
}
Ideally, functions could switch back and forth between these two forms without changing their API, for backwards compatibility reasons. This means you can't just auto-await calls to `async fn`s like Kotlin does- it would need to be a more complex rule.Second, a lot of users want suspension points to show up in the program text the same way `?` does. This is nice for managing invariants- you know when you might be interrupted. (Personally I don't think this is a good reason; the borrow checker and async-aware synchronization primitives would solve the problem with less noise, but it is what it is.)
In that case the concept of async functions disappears and your first function becomes a normal function. The second function remains a Future building function. So I'm tempted to conclude that this problem might be a non-problem, caused by a confusion between async functions and Future building functions. Even though an async function desugars to a Future building function, they are conceptually distinct in the lightweight threads model. With lightweight threads, all functions are async functions. A future building function explicitly builds a delayed computation. The types should be different.
An async function is just like a normal function, except that it may call async APIs (i.e. other async functions). Calling an async function from a normal function is an error; it does not return a future. The programmer never sees that async functions are implemented with Futures under the hood. In particular, an async function is not syntactic sugar for wrapping its body in an async block. We rename the async { ... } keyword to future { ... }, which constructs a future out of the block. You may call async functions in a future block. So if you want to call an async function inside a normal function, you must do future { foo() }, making it syntactically clear that the call is delayed even when the call is made from inside a normal function. The programmer no longer needs to think about how async functions work at all. Don't tell them that future{ foo() } actually will just call foo(), and foo() returns the future, they don't need to know that. The only thing they need to remember is that async functions can only be called from within async functions or future blocks. In all other respects they behave the same as normal functions. All delaying of computation and running computation in parallel is explicit.
IMO, problem 1 only occurs to programmers that have been told that async fn = Future returning function. That's a leaky abstraction; it's syntactic sugar. If you prevent them from developing this notion, the problem simply doesn't occur. To understand the main proposal for async/await you basically have to understand what desugaring the compiler is doing. With the "Explicit future construction, implicit await" you can use async functions and futures without understanding how they work under the hood. It's a non-leaky abstraction.
IMO, problem 2 is a problem for the IDE. The IDE can easily show which function calls are async and which are not.
That is, a function is always allowed to hold onto its arguments until it returns. If its execution is deferred (e.g. `|| the_function(and, its, arguments)`) for whatever reason (e.g. spawning a lightweight thread or async task), the borrow checker has to consider that those arguments may stick around indefinitely.
Of course, it is 100% doable to force people to work around this just by giving future-building functions a different type. But as I described, this means callers have to add or remove an extra `.run()`/`.await()`/etc. if the API ever switches between the two. This is accepted in the world of threads, but not in the world of futures, because we already have a solution which is "just switch to a future-building function, everyone's already awaiting it."
(Personally, while I certainly see it as a real problem, I would rather we just live with it. It's not hard to work around, and we already do it in the world of threads when necessary, which is rarely.)
- functions that can be called asynchronous must be marked with suspend.
- functions marked as suspend can only be called from within a co-routine context. This is an abstraction that gives you a handle on resources consumed by your co-routines and some level of control over that.
- You can create/get a co-routine context in several ways and there's a global context (i.e. the main thread). Useful other contexts could be some web request or some thread pool. A context has dispatcher, a scope, and a few other things.
3) suspend functions calling other suspend functions implicitly await each other, i.e. preserve before/after semantics. It looks like normal code and there are no special keywords needed. IMHO this is genius compared to promise chaining and error handling you deal with in javascript which can become quite messy. Even with async await in js, you still need to return a Promise. In Kotlin all this is implied by using the suspend keyword on the function.
4) await is indeed something you do explicitly in a synchronous function only and it blocks the thread it is happening on. So, it's also something you should mostly avoid.
5) Co-routines can be terminated. This ensures that any still running async calls stop wasting cpu time. This is a problem in e.g. javascript where once you are awaiting something, you have no way to interrupt whatever it is you are awaiting.
6) pre-existing other asynchronous stuff in Java and its various frameworks can be adapted to co-routines quite easily.
This is a complicated topic and I'm sure there are a thing or two here that don't quite map to Rust that easily, which they've probably debated at length. I imagine tight memory and resource control is important for Rust. But it's a nice design for Kotlin at least. Compared to Rust, the development process was interesting as well. There was a long experimental feature cycle (1.1 and 1.2) during which you could opt into using it but during which there were also major changes based on the usage and feedback. I think they learned a lot during this phase. There are still new things coming that are still experimental (e.g. channels).
In any case, I'm a big fan of the idea that async/await is just syntax around something that can be done without the syntax (i.e. wrapping Futures that can otherwise be manipulated without the syntax).
I like the "Unusual other syntaxes: Use a more unusual syntax which no other construction in Rust uses, such future!await." [1] (or future@await). It makes sense because it is in fact something different than what exists anywhere else in Rust so it should receive a commensurate syntactic treatment. This was written off pretty quickly in [1] but it appears the most consistent with language philosophy -- specifically because it's inconsistent with any other language features it should get inconsistent syntax. I think that's what's throwing people off in this process: an attempt to impose 'consistency' on something that just isn't. As such, it'll never feel natural to co-opt existing syntax. Let's embrace it's inconsistency and introduce new syntax.
It supports '?' and '.' natively, and offers a path forward for new similar kinds of postfix operators without making more field names off-limits -- even the expr@match { .. } postfix expression thrown around would fit well. The @-prefixed postfix operator would return a value like all other expressions.
tl;dr: Either the syntax is inconsistent or the semantics are, and IMO, the former is preferable to the latter.
Either way, cool to see this feature moving along! Looking forward to using it no matter how it's spelled out haha.
[1] https://paper.dropbox.com/doc/Await-Syntax-Write-Up--AcIbhZ1...
I'm on the fence about disambiguation via unique punctuation, vs avoiding Perl-like line noise.
foo.bar(..).baz(..).match {
Variant1 => { ... }
Variant2(quux) => { ... }
}
Compared to some Ruby: 5.times {
puts "Hello world!"
}
Note I'm by no means an expert in Ruby or Rust, this is just what I thought of when I saw the syntax.I prefer Kotlin's general approach of .let and similar:
number = foo.bar().baz().let {
match it {
A => 1
B => 2
}
}
Now anyone has the general tool for chaining without needing library authors or language designers to create the API for them.[1] https://doc.rust-lang.org/std/option/enum.Option.html#method..., https://doc.rust-lang.org/std/result/enum.Result.html#method..., https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
let number = foo.bar().baz().match { it =>
it + 1
}; do 5.times {
// ...
}
Where do was just sugar for calling functions that took a closure as the last argument: fn foo(a: A, ..., z: Z, cl: ||) { ... }
foo(a, ..., z, || {
...
})
do foo(a, ..., z) {
...
} do some_array.each |item| {
...
}You can of course already do async things in Rust the same way you do in C: by passing around function pointers and either passing around a handle to the event loop or, more commonly, using a single global handle. But you theoretically could run multiple event loops (one per core, say) and could pass around a pointer to which event loop you wanted to work with and a lot of libevent examples do this. (IMO it's the only correct way to do it, but I have sympathy for wanting to have the global variable.)
This is a little different to Javascript where the event loop is part of the language/runtime. Javascript's "the event loop" model means you can't run more than one event loop per runtime, so it's kind of nonsense to want to pass it around explicitly.
Rust is more like C in this regard. So if I wanted to mix threads and events, or run an event loop per core, or have an event loop that my Fancy HTTP Library manages itself but exposes a blocking interface to, do I lose access to the new fancy `.await` syntax? There's nowhere in this syntax to say which event loop I'm registering myself with. Is there just one global one? Does it get globally registered on runtime boot, and everyone references it? Or is there a thread-local variable for the "current" event loop that this thread knows about?
Even more concerning is how to make _other_ libraries do this than the one I'm writing. If I'm calling into an async library how can I tell that library that I want it to use "an" event loop instead of "the" event loop?
What should I be googling for to answer this? :)
A short version of the answer is that at its core, you create a chain of futures, and then place them on an executor. The executor is responsible for executing them.
Async is sugar for creating a chain of futures. Doing that stuff is a property of the executor. Completely different axis.
(And tokio today has a multi-threaded, work-stealing executor, for example.)
A language should, in my opinion, not depend on syntax highlighting.
There were a number of people who converted code to the various proposals, so that helped.
That's assuming that you know the syntax already. If you're learning the syntax for the first time without the benefit of syntax highlighting, `.await` might be more confusing than it would otherwise be – but I think the point about `.await?`, combined with the familiarity of `await` as a special operation from other languages (as well as it just being a verb rather than a noun), would strongly hint that something different from a field access is going on. If not... well, you can always learn what it does from the documentation, since it'll be one of the first things explained in any kind of async tutorial. I'm a big believer in the concept of "strangeness budget" and avoiding unnecessary syntactic unfamiliarity, but I think the strangeness is very strongly mitigated here. In any case, most people will learn the syntax with the benefit of syntax highlighting, and IMO taking advantage of that is much more defensible than depending on syntax highlighting for readability more generally.
From a historical perspective, in the debate leading up to the switch from `try!()` to `?`, people were worried that `?` would be lost in the noise within long chains, an issue that others said would be mitigated by syntax highlighting. As it turned out, syntax highlighting does help, but `?` is also pretty distinctive without it. I think `.await` will pan out similarly.
More generally, I think that once people get used to the idea of `.await` and it stops being this new weird-looking thing, the mere-exposure effect[1] will subside and people will stop seeing confusion with field access as such a big problem. Well, people already using Rust, at any rate. Ironically, once you get past unfamiliarity, the reverse bias comes into effect, where it becomes unintuitive to think how other people first learning the language will find something weird. But from that perspective, there are a lot of weird things in Rust's syntax already. Adding more is not a good thing, but it's also not as bad as it might seem if everything in Rust seems familiar except this one thing.
I still kind of want postfix macros, though. I saw a couple other neat use cases like `file.write!(...)`
But we don't need user definable postfix macros to have a single `expression.await!()` as a magical macro. There are already magical macros, and to most Rust users `foo!()` means "magic here, read the docs". It would have been syntactically consistent to have `await!()` also mean "magic here, read the docs".
100% of Rust users will recognize the inconsistency of overloading field access syntax. Only a portion of Rust users will dig deep enough into macros to recognize that `expression.await!()` is special and is not defined as a normal macro. By the time a user digs deep enough to realize that, they are ready to understand why that inconsistency was necessary.
With `expression.await` new users may ask about the inconsistency and the answer will be "because reasons you can't understand right now".
(P.s. I'm not trying to start a debate, just trying to answer the question.)
Control flow from a dot-access rubs me just a bit the wrong way - honestly, I'd rather the syntax be a bit cumbersome because if I saw multiple nested `await`s in a single expression, I'd think the code was suspect and review it more, while I'm probably not going to have quite the same reaction for `x.await?.await?.foo.await?`, just because it _looks_ like normal property chaining.
From a language-feel and ergonomics standpoint, I agree. But the Rust team has made it pretty clear why a postfix is much more flexible, and I think we'll grow into it.
I do think it'll continue as a bit of a Rust oddity when compared to other async/await implementations (e.g., Python).
var result = (await (await obj.DoSomething()).SomeOperation()).SomeValue;
In the end, all syntax is magic that you need to get used to, I guess.A quick search has it listed it as a synonym, but I can't find any usage outside tech and it sure seems like a tech-industry/coding erroneous neologism trying to balance the seemingly logical "post" -vs- "pre".
Am I way off the mark here?
It's also commonly used as the name of a piece of email software, but that's also an unrelated usage to this.
RPN and postfix notation refer to the same core idea. From Wikipedia: "Reverse Polish notation (RPN), also known as Polish postfix notation or simply postfix notation, is a mathematical notation in which operators follow their operands, in contrast to Polish notation (PN), in which operators precede their operands."
Can you please explain why you wrote "Reverse polish notation is an entirely different usage"? With a citation, preferably.
Affix/suffix
All of this stuff has different histories and slightly different usage, but yeah.
Just as `?` was introduced, I don't see a good reason ("line noise" doesn't even count as a thought) that they wouldn't introduce postfix notion with `@` `#` `$` or any thing else similar.
If they are looking forward to expanding postfix synax for things like `match`, then this would provide them with the most flexibility and essentially provide a new namespace for those features.
"Line noise" isn't a reason. APL had it right in that consistent syntax (Perl doens't count as consistent) is useful.
match expression
await expression
It feels like a future proposal, to allow these keywords to be chained more conveniently with a postfix. It's cool that this can possibly be generalised for chaining ergonomics. expression.match
expression.await
expression<-match
expression<-awaitAlso, I would expect `await` to have mandatory braces, just as `match`, `if`, `for`, etc. do.
Personally I like the fact that ".await" emphasizes that you are dealing with something fundamentally different from other language constructs, because futures _are_ fundamentally different.
Too many incompatible platform-specific APIs: epoll and AIO on Linux, kqueue on BSD and OSX, IOCP and new thread pool API on Windows. I’m pretty sure I forgot couple others, and each of them have non-trivial amount of quirks, bugs, and performance-ruining edge cases. Also these APIs are not directly compatible to each other.
To be usable, async IO needs to be integrated into the rest of IO. You can’t just place that on top, e.g. Java did that, IMO didn’t work particularly well.
The combination of the above makes creating good cross-platform abstraction for async IO challenging.
Not saying impossible, but it’s very hard to do.
I’ve tried once in C++, for that project I needed epoll and iocp, but I wasn’t able within reasonable time. Ended up swapping relatively large IO-related parts of my app depending on platform.
I've looked at the library, it doesn't support anything besides epoll and IOCP, i.e. no BSD or OSX support, no AIO on Linux (the kernel one, not POSIX).
You probably don't want to consume IOCP API on Windows anymore, Vista introduced higher level and easier to use StartThreadpoolIo and friends.
Also on Windows, even with IOCP, you don't want to split async IO from thread pool. The OS kernel manages them both at the same time. Work stealing or other custom scheduling is usually slower than what kernel does.
I found this issue where they're discussing rewriting the Windows implementation using the library `wepoll`.
https://github.com/tokio-rs/gsoc/issues/3
What would be the advantages of supporting AIO on Linux?
> The primary argument in favor of postfix was its better composability with methods and the ? operator.
Either the syntax is inconsistent or the semantics are, and IMO, the former is preferable to the latter.
[a+2 for a in as if a > 3]
Vs
as.filter(a -> a > 3).map(a -> a + 2)
Sometimes I even wonder why variable assignment has to precede the assigned expression.
I think there's a good discussion to be had on preferring either prefix or postfix operators, but the answer to this question (which is also the answer to the question "why are we so accustomed to prefix keywords?") is easy: because ALGOL did it.
HKT would make things considerably nicer.
1. Use a postfix ?! instead of .await
2. Use a postfix ?? instead of .await?
3. Use the await keyword only in the "for await" construct
Then the common case becomes:
let resp = http::get(url)??.to_string()
Which, imo, is a bit easier to parse than: let resp = http::get(url).await?.to_string()
This would make it easier to follow the core logic in async code, the same way that ? made error handling so much cleaner in Rust.I agree that the syntax should have `await' somewhere, and the observation that it "clearly" is not a field access is actually credible to me. This also open the possibility to have other kinds of postfix keyword e.g. .try or .match