Skip to content

Commit

Permalink
Editorial cleanup on expressions (part 1)
Browse files Browse the repository at this point in the history
* Use "the syntax of" uniformly.
* Use asterisks for all defined terms.
* Define more terms, espcially in the syntax section.
** Reword things so that definitions are generally first.
** I did not necessarily go with the best wording; the idea is to
   improve, not perfect. I still need to dedicate time to each
   expressions individually.
* Remove usage of "the compiler" and "Rust".
** This also involved rewording.
** How to deal with closure types and closure expressions is gonna be
   an interesting question to solve. I avoided solving it here.
* Remove non-normative information or put them in a `Note`.
* A few added section headers
* Move links to the bottom

Note that I've left quite a few nonsensical statements alone, such as
any that use "denote". They'll be treated separately.

About halfway through the list of expressions and this PR is getting
large. So I'm gonna cut this one here, stopping at grouped expressions
in the alphabetical list.
  • Loading branch information
Havvy committed Feb 27, 2021
1 parent 361367c commit a065d3e
Show file tree
Hide file tree
Showing 8 changed files with 130 additions and 93 deletions.
2 changes: 1 addition & 1 deletion src/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,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
16 changes: 10 additions & 6 deletions src/expressions/array-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@
> &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 operands 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].
The syntax for the second form is two operands separated by a semicolon (`;`) enclosed in square brackets.
The operand 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.
If the operand 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.

When the repeat expression `a` is a constant item, it is evaluated `b` times.
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.

Expand Down Expand Up @@ -49,7 +53,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
30 changes: 14 additions & 16 deletions src/expressions/await-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
> _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 operand with a type that implements the Future trait, `.`, 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.

Expand All @@ -16,29 +16,16 @@ More specifically, an `<expr>.await` expression has the following effect.
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 `<expr>.await` expression is roughly equivalent to the following non-normative desugaring:

<!-- ignore: example expansion -->
```rust,ignore
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
69 changes: 35 additions & 34 deletions src/expressions/block-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ 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 [statements], then an optional 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.
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.
Expand All @@ -43,36 +45,38 @@ 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.
Blocks are always [value expressions] and evaluate the last operand in value expression context.

```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();
}
```
> **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
15 changes: 8 additions & 7 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 operand, the *function operand*, followed by a parenthesized comma-separated list of operands, 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.
An automatic borrow will be taken if needed.
Rust will also automatically dereference `f` as required.
`f` will also be automatically dereferences as required.

Some examples of call expressions:

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

## Disambiguating Function Calls

Rust treats all function calls as sugar for a more explicit, [fully-qualified syntax].
All function calls are 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.

> **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
38 changes: 21 additions & 17 deletions src/expressions/closure-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,28 @@
> _ClosureParam_ :\
> &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup> [_Pattern_]&nbsp;( `:` [_Type_] )<sup>?</sup>
A _closure expression_, also know as a lambda expression or a lambda, defines a closure and denotes it as a value, in a single expression.
A closure expression is a pipe-symbol-delimited (`|`) list of irrefutable [patterns] followed by an expression.
Type annotations may optionally be added for the type of the parameters or for the return type.
If there is a return type, the expression used for the body of the closure must be a normal [block].
A closure expression also may begin with the `move` keyword before the initial `|`.
A *closure expression*, also know as a lambda expression or a lambda, defines a [closure type] and evaluates to a value of that type.
The syntax for a closure expression is an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns], the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, the *return type*, and then an operand, the *closure body*.
The optional type after each pattern is a type annotation for the pattern.
If there is a return type, the closure body must be a [block].

A closure expression denotes a function that maps a list of parameters onto the expression that follows the parameters.
Just like a [`let` binding], the parameters are irrefutable [patterns], whose type annotation is optional and will be inferred from context if not given.
Just like a [`let` binding], the closure parameters are irrefutable [patterns], whose type annotation is optional and will be inferred from context if not given.
Each closure expression has a unique, anonymous type.

Closure expressions are most useful when passing functions as arguments to other functions, as an abbreviation for defining and capturing a separate function.

Significantly, closure expressions _capture their environment_, which regular [function definitions] do not.
Without the `move` keyword, the closure expression [infers how it captures each variable from its environment](../types/closure.md#capture-modes), preferring to capture by shared reference, effectively borrowing all outer variables mentioned inside the closure's body.
If needed the compiler will infer that instead mutable references should be taken, or that the values should be moved or copied (depending on their type) from the environment.
A closure can be forced to capture its environment by copying or moving values by prefixing it with the `move` keyword.
This is often used to ensure that the closure's type is `'static`.
This is often used to ensure that the closure's lifetime is `'static`.

## Closure trait implementations

Which traits the closure type implement depends on how variables are captured and the types of the captured variables.
See the [call traits and coercions] chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`.
The closure type implements [`Send`] and [`Sync`] if the type of every captured variable also implements the trait.

The compiler will determine which of the [closure traits](../types/closure.md#call-traits-and-coercions) the closure's type will implement by how it acts on its captured variables.
The closure will also implement [`Send`](../special-types-and-traits.md#send) and/or [`Sync`](../special-types-and-traits.md#sync) if all of its captured types do.
These traits allow functions to accept closures using generics, even though the exact types can't be named.
## Example

In this example, we define a function `ten_times` that takes a higher-order function argument, and we then call it with a closure expression as an argument, followed by a closure expression that moves values from its environment.

Expand All @@ -55,15 +56,18 @@ ten_times(move |j| println!("{}, {}", word, j));

Attributes on closure parameters follow the same rules and restrictions as [regular function parameters].

[block]: block-expr.md
[function definitions]: ../items/functions.md
[patterns]: ../patterns.md
[regular function parameters]: ../items/functions.md#attributes-on-function-parameters

[_Expression_]: ../expressions.md
[_BlockExpression_]: block-expr.md
[_TypeNoBounds_]: ../types.md#type-expressions
[_Pattern_]: ../patterns.md
[_Type_]: ../types.md#type-expressions
[`let` binding]: ../statements.md#let-statements
[`Send`]: ../special-types-and-traits.md#send
[`Sync`]: ../special-types-and-traits.md#sync
[_OuterAttribute_]: ../attributes.md
[block]: block-expr.md
[call traits and coercions]: ../types/closure.md#call-traits-and-coercions
[closure type]: ../types/closure.md
[function definitions]: ../items/functions.md
[patterns]: ../patterns.md
[regular function parameters]: ../items/functions.md#attributes-on-function-parameters
Loading

0 comments on commit a065d3e

Please sign in to comment.