Skip to content

Editorial cleanup on expressions (part 1) #967

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

Merged
merged 4 commits into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ In this way, the structure of expressions dictates the structure of execution.
Blocks are just another kind of expression, so blocks, statements, expressions,
and blocks again can recursively nest inside each other to an arbitrary depth.

> **Note**: We give names to the operands of expressions so that we may discuss
> them, but these names are not stable and may be changed.
Comment on lines +58 to +59
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious why this needs to be stated. Are you concerned that other people will start using these names, and you don't want that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mainly because I'm coming up with them off the spot without any rigorous discussion or approval from the lang team. I might try an RFC for making these terms part of the language, and dealing with the bikeshed that that entails. I also want to be able to freely change them if we do find better names.


## Expression precedence

The precedence of Rust operators and expressions is ordered as follows, going
Expand Down Expand Up @@ -137,7 +140,7 @@ assert_eq!(
## Place Expressions and Value Expressions

Expressions are divided into two main categories: place expressions and
value expressions. Likewise within each expression, sub-expressions may occur
value expressions. Likewise within each expression, operands may occur
in either place context or value context. The evaluation of an expression
depends both on its own category and the context it occurs within.

Expand Down
28 changes: 18 additions & 10 deletions src/expressions/array-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,28 @@
> &nbsp;&nbsp; &nbsp;&nbsp; [_Expression_] ( `,` [_Expression_] )<sup>\*</sup> `,`<sup>?</sup>\
> &nbsp;&nbsp; | [_Expression_] `;` [_Expression_]

An _[array] expression_ can be written by enclosing zero or more comma-separated expressions of uniform type in square brackets.
*Array expressions* construct [arrays][array].
Array expressions come in two forms.

The first form lists out every value in the array.
The syntax for this form is a comma-separated list of expressions of uniform type enclosed in square brackets.
This produces an array containing each of these values in the order they are written.

Alternatively there can be exactly two expressions inside the brackets, separated by a semicolon.
The expression after the `;` must have type `usize` and be a [constant expression], such as a [literal] or a [constant item].
`[a; b]` creates an array containing `b` copies of the value of `a`.
If the expression after the semicolon has a value greater than 1 then this requires that the type of `a` is [`Copy`], or `a` must be a path to a constant item.
The syntax for the second form is two expressions separated by a semicolon (`;`) enclosed in square brackets.
The expression before the `;` is called the *repeat operand*.
The expression after the `;` is called the *length operand*.
It must have type `usize` and be a [constant expression], such as a [literal] or a [constant item].
An array expression of this form creates an array with the length of the value of the legnth operand with each element a copy of the repeat operand.
That is, `[a; b]` creates an array containing `b` copies of the value of `a`.
If the length operand has a value greater than 1 then this requires that the type of the repeat operand is [`Copy`] or that it must be a [path] to a constant item.

When the repeat expression `a` is a constant item, it is evaluated `b` times.
If `b` is 0, the constant item is not evaluated at all.
For expressions that are not a constant item, it is evaluated exactly once, and then the result is copied `b` times.
When the repeat operand is a constant item, it is evaluated the length operand's value times.
If that value is `0`, then the constant item is not evaluated at all.
For expressions that are not a constant item, it is evaluated exactly once, and then the result is copied the length operand's value times.

<div class="warning">

Warning: In the case where `b` is 0, and `a` is a non-constant item, there is currently a bug in `rustc` where the value `a` is evaluated but not dropped, thus causing a leak.
Warning: In the case where the length operand is 0, and the repeat operand is a non-constant item, there is currently a bug in `rustc` where the value `a` is evaluated but not dropped, thus causing a leak.
See [issue #74836](https://github.com/rust-lang/rust/issues/74836).

</div>
Expand All @@ -49,7 +56,7 @@ const EMPTY: Vec<i32> = Vec::new();
> _IndexExpression_ :\
> &nbsp;&nbsp; [_Expression_] `[` [_Expression_] `]`

[Array] and [slice]-typed expressions can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them.
[Array] and [slice]-typed values can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them.
When the array is mutable, the resulting [memory location] can be assigned to.

For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context.
Expand Down Expand Up @@ -91,4 +98,5 @@ The array index expression can be implemented for types other than arrays and sl
[constant item]: ../items/constant-items.md
[literal]: ../tokens.md#literals
[memory location]: ../expressions.md#place-expressions-and-value-expressions
[path]: path-expr.md
[slice]: ../types/slice.md
36 changes: 17 additions & 19 deletions src/expressions/await-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,32 @@
> _AwaitExpression_ :\
> &nbsp;&nbsp; [_Expression_] `.` `await`

*Await expressions* suspend the current computation until the given future is ready to produce a value.
The syntax for an await expression is an expression with a type that implements the [Future] trait, called the *future operand*, then the token `.`, and then the `await` keyword.
Await expressions are legal only within an [async context], like an [`async fn`] or an [`async` block].
They operate on a [future].
Their effect is to suspend the current computation until the given future is ready to produce a value.

More specifically, an `<expr>.await` expression has the following effect.
More specifically, an await expression has the following effect.

1. Evaluate `<expr>` to a [future] `tmp`;
1. Evaluate the future operand to a [future] `tmp`;
2. Pin `tmp` using [`Pin::new_unchecked`];
3. This pinned future is then polled by calling the [`Future::poll`] method and passing it the current [task context](#task-context);
3. If the call to `poll` returns [`Poll::Pending`], then the future returns `Poll::Pending`, suspending its state so that, when the surrounding async context is re-polled,execution returns to step 2;
4. Otherwise the call to `poll` must have returned [`Poll::Ready`], in which case the value contained in the [`Poll::Ready`] variant is used as the result of the `await` expression itself.

[`async fn`]: ../items/functions.md#async-functions
[`async` block]: block-expr.md#async-blocks
[future]: ../../std/future/trait.Future.html
[_Expression_]: ../expressions.md
[`Future::poll`]: ../../std/future/trait.Future.html#tymethod.poll
[`Context`]: ../../std/task/struct.Context.html
[`Pin::new_unchecked`]: ../../std/pin/struct.Pin.html#method.new_unchecked
[`Poll::Pending`]: ../../std/task/enum.Poll.html#variant.Pending
[`Poll::Ready`]: ../../std/task/enum.Poll.html#variant.Ready

> **Edition differences**: Await expressions are only available beginning with Rust 2018.

## Task context

The task context refers to the [`Context`] which was supplied to the current [async context] when the async context itself was polled.
Because `await` expressions are only legal in an async context, there must be some task context available.

[`Context`]: ../../std/task/struct.Context.html
[async context]: ../expressions/block-expr.md#async-context

## Approximate desugaring

Effectively, an `<expr>.await` expression is roughly equivalent to the following (this desugaring is not normative):
Effectively, an await expression is roughly equivalent to the following non-normative desugaring:

<!-- ignore: example expansion -->
```rust,ignore
match /* <expr> */ {
match future_operand {
mut pinned => loop {
let mut pin = unsafe { Pin::new_unchecked(&mut pinned) };
match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) {
Expand All @@ -55,3 +42,14 @@ match /* <expr> */ {

where the `yield` pseudo-code returns `Poll::Pending` and, when re-invoked, resumes execution from that point.
The variable `current_context` refers to the context taken from the async environment.

[_Expression_]: ../expressions.md
[`async fn`]: ../items/functions.md#async-functions
[`async` block]: block-expr.md#async-blocks
[`context`]: ../../std/task/struct.Context.html
[`future::poll`]: ../../std/future/trait.Future.html#tymethod.poll
[`pin::new_unchecked`]: ../../std/pin/struct.Pin.html#method.new_unchecked
[`poll::Pending`]: ../../std/task/enum.Poll.html#variant.Pending
[`poll::Ready`]: ../../std/task/enum.Poll.html#variant.Ready
[async context]: ../expressions/block-expr.md#async-context
[future]: ../../std/future/trait.Future.html
75 changes: 38 additions & 37 deletions src/expressions/block-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@ A *block expression*, or *block*, is a control flow expression and anonymous nam
As a control flow expression, a block sequentially executes its component non-item declaration statements and then its final optional expression.
As an anonymous namespace scope, item declarations are only in scope inside the block itself and variables declared by `let` statements are in scope from the next statement until the end of the block.

Blocks are written as `{`, then any [inner attributes], then [statements], then an optional expression, and finally a `}`.
Statements are usually required to be followed by a semicolon, with two exceptions.
Item declaration statements do not need to be followed by a semicolon.
Expression statements usually require a following semicolon except if its outer expression is a flow control expression.
The syntax for a block is `{`, then any [inner attributes], then any number of [statements], then an optional expression, called the final operand, and finally a `}`.

Statements are usually required to be followed by a semicolon, with two exceptions:

1. Item declaration statements do not need to be followed by a semicolon.
2. Expression statements usually require a following semicolon except if its outer expression is a flow control expression.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there should be a blank like after this, so that the sentence "Furthermore, extra semicolons..." is not combined with the last point. At least, the way I'm reading it, it doesn't seem like it should be combined.


Furthermore, extra semicolons between statements are allowed, but these semicolons do not affect semantics.

When evaluating a block expression, each statement, except for item declaration statements, is executed sequentially.
Then the final expression is executed, if given.
Then the final operand is executed, if given.

The type of a block is the type of the final expression, or `()` if the final expression is omitted.
The type of a block is the type of the final operand, or `()` if the final operand is omitted.

```rust
# fn fn_call() {}
Expand All @@ -43,36 +46,37 @@ assert_eq!(5, five);

> Note: As a control flow expression, if a block expression is the outer expression of an expression statement, the expected type is `()` unless it is followed immediately by a semicolon.

Blocks are always [value expressions] and evaluate the last expression in value expression context.
This can be used to force moving a value if really needed.
For example, the following example fails on the call to `consume_self` because the struct was moved out of `s` in the block expression.

```rust,compile_fail
struct Struct;

impl Struct {
fn consume_self(self) {}
fn borrow_self(&self) {}
}

fn move_by_block_expression() {
let s = Struct;

// Move the value out of `s` in the block expression.
(&{ s }).borrow_self();
Blocks are always [value expressions] and evaluate the last operand in value expression context.

// Fails to execute because `s` is moved out of.
s.consume_self();
}
```
> **Note**: This can be used to force moving a value if really needed.
> For example, the following example fails on the call to `consume_self` because the struct was moved out of `s` in the block expression.
>
> ```rust,compile_fail
> struct Struct;
>
> impl Struct {
> fn consume_self(self) {}
> fn borrow_self(&self) {}
> }
>
> fn move_by_block_expression() {
> let s = Struct;
>
> // Move the value out of `s` in the block expression.
> (&{ s }).borrow_self();
>
> // Fails to execute because `s` is moved out of.
> s.consume_self();
> }
> ```

## `async` blocks

> **<sup>Syntax</sup>**\
> _AsyncBlockExpression_ :\
> &nbsp;&nbsp; `async` `move`<sup>?</sup> _BlockExpression_

An *async block* is a variant of a block expression which evaluates to a *future*.
An *async block* is a variant of a block expression which evaluates to a future.
The final expression of the block, if present, determines the result value of the future.

Executing an async block is similar to executing a closure expression:
Expand All @@ -84,26 +88,17 @@ The actual data format for this type is unspecified.

> **Edition differences**: Async blocks are only available beginning with Rust 2018.

[`std::ops::Fn`]: ../../std/ops/trait.Fn.html
[`std::future::Future`]: ../../std/future/trait.Future.html

### Capture modes

Async blocks capture variables from their environment using the same [capture modes] as closures.
Like closures, when written `async { .. }` the capture mode for each variable will be inferred from the content of the block.
`async move { .. }` blocks however will move all referenced variables into the resulting future.

[capture modes]: ../types/closure.md#capture-modes
[shared references]: ../types/pointer.md#shared-references-
[mutable reference]: ../types/pointer.md#mutables-references-

### Async context

Because async blocks construct a future, they define an **async context** which can in turn contain [`await` expressions].
Async contexts are established by async blocks as well as the bodies of async functions, whose semantics are defined in terms of async blocks.

[`await` expressions]: await-expr.md

### Control-flow operators

Async blocks act like a function boundary, much like closures.
Expand Down Expand Up @@ -171,16 +166,22 @@ fn is_unix_platform() -> bool {
[_ExpressionWithoutBlock_]: ../expressions.md
[_InnerAttribute_]: ../attributes.md
[_Statement_]: ../statements.md
[`await` expressions]: await-expr.md
[`cfg`]: ../conditional-compilation.md
[`for`]: loop-expr.md#iterator-loops
[`loop`]: loop-expr.md#infinite-loops
[`std::ops::Fn`]: ../../std/ops/trait.Fn.html
[`std::future::Future`]: ../../std/future/trait.Future.html
[`while let`]: loop-expr.md#predicate-pattern-loops
[`while`]: loop-expr.md#predicate-loops
[array expressions]: array-expr.md
[call expressions]: call-expr.md
[capture modes]: ../types/closure.md#capture-modes
[function]: ../items/functions.md
[inner attributes]: ../attributes.md
[method]: ../items/associated-items.md#methods
[mutable reference]: ../types/pointer.md#mutables-references-
[shared references]: ../types/pointer.md#shared-references-
[statement]: ../statements.md
[statements]: ../statements.md
[struct]: struct-expr.md
Expand Down
22 changes: 12 additions & 10 deletions src/expressions/call-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
> _CallParams_ :\
> &nbsp;&nbsp; [_Expression_]&nbsp;( `,` [_Expression_] )<sup>\*</sup> `,`<sup>?</sup>

A _call expression_ consists of an expression followed by a parenthesized expression-list.
It invokes a function, providing zero or more input variables.
A *call expression* calls a function.
The syntax of a call expression is an expression, called the *function operand*, followed by a parenthesized comma-separated list of expression, called the *argument operands*.
If the function eventually returns, then the expression completes.
For [non-function types](../types/function-item.md), the expression f(...) uses the method on one of the [`std::ops::Fn`], [`std::ops::FnMut`] or [`std::ops::FnOnce`] traits, which differ in whether they take the type by reference, mutable reference, or take ownership respectively.
For [non-function types], the expression `f(...)` uses the method on one of the [`std::ops::Fn`], [`std::ops::FnMut`] or [`std::ops::FnOnce`] traits, which differ in whether they take the type by reference, mutable reference, or take ownership respectively.
An automatic borrow will be taken if needed.
Rust will also automatically dereference `f` as required.
The function operand will also be [automatically dereferenced] as required.

Some examples of call expressions:

```rust
Expand All @@ -23,13 +24,12 @@ let name: &'static str = (|| "Rust")();

## Disambiguating Function Calls

Rust treats all function calls as sugar for a more explicit, [fully-qualified syntax].
Upon compilation, Rust will desugar all function calls into the explicit form.
Rust may sometimes require you to qualify function calls with trait, depending on the ambiguity of a call in light of in-scope items.
All function calls are sugar for a more explicit [fully-qualified syntax].
Function calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items.

> **Note**: In the past, the Rust community used the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", in documentation, issues, RFCs, and other community writings.
> However, the term lacks descriptive power and potentially confuses the issue at hand.
> We mention it here for searchability's sake.
> **Note**: In the past, the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", have been used in documentation, issues, RFCs, and other community writings.
> However, these terms lack descriptive power and potentially confuse the issue at hand.
> We mention them here for searchability's sake.

Several situations often occur which result in ambiguities about the receiver or referent of method or associated function calls.
These situations may include:
Expand Down Expand Up @@ -92,4 +92,6 @@ Refer to [RFC 132] for further details and motivations.
[`std::ops::FnMut`]: ../../std/ops/trait.FnMut.html
[`std::ops::FnOnce`]: ../../std/ops/trait.FnOnce.html
[`std::ops::Fn`]: ../../std/ops/trait.Fn.html
[automatically dereferenced]: field-expr.md#automatic-dereferencing
[fully-qualified syntax]: ../paths.md#qualified-paths
[non-function types]: ../types/function-item.md
Loading