Skip to content

Expression editing #1003

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
175 changes: 84 additions & 91 deletions src/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,33 @@
>       | [_MatchExpression_]\
>    )

An expression may have two roles: it always produces a *value*, and it may have
*effects* (otherwise known as "side effects"). An expression *evaluates to* a
value, and has effects during *evaluation*. Many expressions contain
sub-expressions, called the *operands* of the expression. The meaning of each
kind of expression dictates several things:
Expressions are the fundamental unit of computation.
When evaluated, they may have *effects* and evaluates to either a value or place.
Copy link
Member

Choose a reason for hiding this comment

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

I think we should probably keep the (otherwise known as "side effects") part


Where expressions are allowed are *expression contexts*.
Copy link
Member

Choose a reason for hiding this comment

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

This sentence sounds rather awkward. What is it you are trying to say? E.g.
"The syntactic positions that permit expressions to be written are called 'expression contexts'."

Expressions commonly contain sub-expressions, called the *operands* of the expression.

The meaning of each kind of expression dictates several things:

* Whether or not to evaluate the operands when evaluating the expression
* The order in which to evaluate the operands
* How to combine the operands' values to obtain the value of the expression
* How to combine the operands' values to obtain the value or place of the expression
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
* How to combine the operands' values to obtain the value or place of the expression
* How to combine the operands' values or places to obtain the value or place of the expression

Expressions like place.field have operands that are places, so I think if we want to be consistent we need to repeat this 'or place'.

Or we could find some term for "the result of evalauting an expression", i.e., a term for "value or place". Usually that term is "value" but we already burned that. In the Stacked Borrows paper formalization, we hence used the term "result".


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.
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.
> **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.

## Expression precedence

The precedence of Rust operators and expressions is ordered as follows, going
from strong to weak. Binary Operators at the same precedence level are grouped
in the order given by their associativity.
The grammar for expressions as presented in this book is wrong.
It purposefully ignores that certain operands cannot be certain expressions due to precedence.
For example, `a * b + c` is actually parsed as an addition operator expression with the multiplication operator expression as its left operand.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
For example, `a * b + c` is actually parsed as an addition operator expression with the multiplication operator expression as its left operand.
For example, `a * b + c` is actually parsed as an addition operator expression with the multiplication operator expression as its left operand (like `(a * b) + c`).

The grammar, taking precedence into account, is too unwieldy to easily read and understand.

The precedence of operators and expressions is ordered as follows, going from strongest to weakest.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Suggested change
The precedence of operators and expressions is ordered as follows, going from strongest to weakest.
The precedence of operators and expressions is ordered, from strongest to weakest, in the following table.

Binary Operators at the same precedence level are grouped in the order given by their associativity.
Expressions in this table cannot have operands that are expressions lower in the table.
Copy link
Member

Choose a reason for hiding this comment

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

maybe say something here about how you can have operands that are lower precedence if wrapped in parenthesis or similar -- we don't want to imply it's impossible to write (a + b) * c after all

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have that as a note after the table. I could put it before the table.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I could also put a * (b + c) in the example as well.


| Operator/Expression | Associativity |
|-----------------------------|---------------------|
Expand All @@ -86,11 +91,12 @@ in the order given by their associativity.
| `=` `+=` `-=` `*=` `/=` `%=` <br> `&=` <code>&#124;=</code> `^=` `<<=` `>>=` | right to left |
| `return` `break` closures | |

> **Note**: Wrapping an expression with a [parenthetical expression][paren] increases its precedence.

## Evaluation order of operands

The following list of expressions all evaluate their operands the same way, as
described after the list. Other expressions either don't take operands or
evaluate them conditionally as described on their respective pages.
The following list of expressions all evaluate their operands the same way, as described after the list.
Other expressions either don't take operands or evaluate them conditionally as described on their respective pages.

* Dereference expression
* Error propagation expression
Expand All @@ -112,15 +118,12 @@ evaluate them conditionally as described on their respective pages.
* Range expression
* Return expression

The operands of these expressions are evaluated prior to applying the effects of
the expression. Expressions taking multiple operands are evaluated left to right
as written in the source code.
The operands of these expressions are evaluated prior to applying the effects of the expression.
Expressions taking multiple operands are evaluated left to right as written in the source code.

> **Note**: Which subexpressions are the operands of an expression is
> determined by expression precedence as per the previous section.
> **Note**: Which subexpressions are the operands of an expression is determined by expression precedence as per the previous section.

For example, the two `next` method calls will always be called in the same
order:
For example, the two `next` method calls will always be called in the same order:

```rust
# // Using vec instead of array to avoid references
Expand All @@ -133,96 +136,88 @@ assert_eq!(
);
```

> **Note**: Since this is applied recursively, these expressions are also
> evaluated from innermost to outermost, ignoring siblings until there are no
> inner subexpressions.
> **Note**: Since this is applied recursively, these expressions are also evaluated from innermost to outermost, ignoring siblings until there are no inner subexpressions.

## Place Expressions and Value Expressions
## Expression categories

Expressions are divided into two main categories: place expressions and
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.
<!-- This section was renamed, but heavily linked to. So adding this span to keep the links working. -->
<span id="place-expressions-and-value-expressions"></span>

A *place expression* is an expression that represents a memory location. These
expressions are [paths] which refer to local variables, [static variables],
[dereferences][deref] (`*expr`), [array indexing] expressions (`expr[expr]`),
[field] references (`expr.f`) and parenthesized place expressions. All other
expressions are value expressions.
Expressions and expression contexts are divided into two *expression categories*: *place* and *value*.
For expressions, what they evaluate into determines their categories.
Copy link
Member

Choose a reason for hiding this comment

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

This feels awkward. We already established the "place or value" dichotomy earlier, so IMO it'd be better to say upfront (L45) that there are "place expressions" and "value expressions" -- or we find some way to not make the place/value distinction at all until here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

My thought was that L45 gives a summary, and then this section expands upon the idea. It would feel weird to not include the dichotomy in the main definition but including the terms in the main definition would be more detail then necessary.

Also, the fact that the category exists for both the expression and the expression context makes this harder to describe.

Copy link
Member

Choose a reason for hiding this comment

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

Also, the fact that the category exists for both the expression and the expression context makes this harder to describe.

These are not two independent facts, so maybe there is a way to present them as one fact? There are two kinds of expressions, basically two kinds of "non-terminals" in the grammar (ValExpr, PlaceExpr), so naturally there are two questions: which class does eache xpression fall in, and which Expr in the grammar is refined to each of these two non-terminals?

Expressions that evaluate to a value are *value expressions* while those that evaluate to a place are *place expressions*.
For expression contexts, whether they operate on a place or value determines their context.
Copy link
Member

Choose a reason for hiding this comment

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

I have no idea what this last sentence is supposed to tell me.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm, I'll think of a way to phrase it better.


A *value expression* is an expression that represents an actual value.
Evaluating an expression in the opposite expression context has effects after evaluation of the expression to produce the expected place or value of the context.
Copy link
Member

Choose a reason for hiding this comment

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

I only understood this sentence after reading the rest of this paragraph. What about something more like "When a place expression is evaluated in value context or vice versa, extra effects apply to perform the required conversion"?

When evaluating a value expression in place expression context, a temporary place is initialized to that value.
When evaluating a place expression in value expression context, the value at that place is read, moving or copying it.

The following contexts are *place expression* contexts:
The following lists all place expressions.
Expressions not listed here are value expressions.

* The left operand of an [assignment][assign] or [compound assignment]
expression.
* [Paths] which refer to local variables or [static variables].
Copy link
Member

Choose a reason for hiding this comment

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

Aren't all paths place expressions?
This sounds like only some paths are place expressions.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I actually don't know. This was here beforehand.

Copy link
Member

Choose a reason for hiding this comment

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

Maybe this was meant as "Paths, which refer to ...". IOW, this is a definition of "Paths".

* [The dereference operator][deref]
* [Field access expressions][field]
* [Tuple indexing expressions]
* [Array indexing expressions]
* [Parenthetical expressions][paren] when its enclosed operand is a place expression

The following list all place expression contexts.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
The following list all place expression contexts.
The following lists all place expression contexts.

All other contexts are value expression contexts.

* The initializer of a [let statement].
* The assigned place operand of an [assignment][assign] or [compound assignment] expression.
* The operand of a unary [borrow] or [dereference][deref] operator.
Copy link
Member

Choose a reason for hiding this comment

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

Should "address-of operator" be listed here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's in your PR which I need to get back to. But my work schedule this week is night/morning/night/morning and I had a migraine over my weekend. I'll rebase against master once that one is merged.

Copy link
Member

Choose a reason for hiding this comment

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

No worries, get a good cup of sleep first. :)

* The operand of a field expression.
* The container operand of a field expression.
Copy link
Member

Choose a reason for hiding this comment

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

What's a "container operand"?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's the operand of the field expression, given a name. See the field expression page, which I should add a link to on this list.

Copy link
Member

Choose a reason for hiding this comment

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

That name strikes me as rather counterintuitive. Maybe "base" would be better?

Since there is only one operand, just saying "the operand" would also work IMO.

* The indexed operand of an array indexing expression.
* The operand of any [implicit borrow].
* The initializer of a [let statement].
* The [scrutinee] of an [`if let`], [`match`][match], or [`while let`]
expression.
* The base of a [functional update] struct expression.
* The [scrutinee] operand of an [`if let`], [`match`][match], or [`while let`] expression.
* The base operand of a [functional update] struct expression.

> Note: Historically, place expressions were called *lvalues* and value
> expressions were called *rvalues*.
> Note: Historically, place expressions were called *lvalues* and value expressions were called *rvalues*.

### Moved and copied types

When a place expression is evaluated in a value expression context, or is bound
by value in a pattern, it denotes the value held _in_ that memory location. If
the type of that value implements [`Copy`], then the value will be copied. In
the remaining situations if that type is [`Sized`], then it may be possible to
move the value. Only the following place expressions may be moved out of:
When a place expression is evaluated in a value expression context, or is bound by value in a pattern, it denotes the value held _in_ that memory location.
If the type of that value implements [`Copy`], then the value will be copied.
In the remaining situations if that type is [`Sized`], then it may be possible to move the value.
Only the following place expressions may be moved out of:

* [Variables] which are not currently borrowed.
* [Temporary values](#temporaries).
* [Fields][field] of a place expression which can be moved out of and
doesn't implement [`Drop`].
* The result of [dereferencing][deref] an expression with type [`Box<T>`] and
that can also be moved out of.
* [Fields][field] of a place expression which can be moved out of and doesn't implement [`Drop`].
* The result of [dereferencing][deref] an expression with type [`Box<T>`] and that can also be moved out of.

Moving out of a place expression that evaluates to a local variable, the
location is deinitialized and cannot be read from again until it is
reinitialized. In all other cases, trying to use a place expression in a value
expression context is an error.
Moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized.
In all other cases, trying to use a place expression in a value expression context is an error.

### Mutability

For a place expression to be [assigned][assign] to, mutably [borrowed][borrow],
[implicitly mutably borrowed], or bound to a pattern containing `ref mut` it
must be _mutable_. We call these *mutable place expressions*. In contrast,
other place expressions are called *immutable place expressions*.
For a place expression to be [assigned][assign] to, mutably [borrowed][borrow], [implicitly mutably borrowed], or bound to a pattern containing `ref mut` it must be _mutable_.
We call these *mutable place expressions*.
In contrast, other place expressions are called *immutable place expressions*.

The following expressions can be mutable place expression contexts:

* Mutable [variables], which are not currently borrowed.
* [Mutable `static` items].
* [Temporary values].
* [Fields][field], this evaluates the subexpression in a mutable place
expression context.
* [Fields][field], this evaluates the subexpression in a mutable place expression context.
* [Dereferences][deref] of a `*mut T` pointer.
* Dereference of a variable, or field of a variable, with type `&mut T`. Note:
This is an exception to the requirement of the next rule.
* Dereferences of a type that implements `DerefMut`, this then requires that
the value being dereferenced is evaluated is a mutable place expression context.
* [Array indexing] of a type that implements `IndexMut`, this
then evaluates the value being indexed, but not the index, in mutable place
expression context.
* Dereference of a variable, or field of a variable, with type `&mut T`.
Note: This is an exception to the requirement of the next rule.
* Dereferences of a type that implements `DerefMut`, this then requires that the value being dereferenced is evaluated is a mutable place expression context.
* [Array indexing expressions] of a type that implements `IndexMut`, this then evaluates the value being indexed, but not the index, in mutable place expression context.

### Temporaries

When using a value expression in most place expression contexts, a temporary
unnamed memory location is created initialized to that value and the expression
evaluates to that location instead, except if [promoted] to a `static`. The
[drop scope] of the temporary is usually the end of the enclosing statement.
When using a value expression in most place expression contexts, a temporary unnamed memory location is created initialized to that value and the expression evaluates to that location instead, except if [promoted] to a `static`.
The [drop scope] of the temporary is usually the end of the enclosing statement.

### Implicit Borrows

Certain expressions will treat an expression as a place expression by implicitly
borrowing it. For example, it is possible to compare two unsized [slices][slice] for
equality directly, because the `==` operator implicitly borrows it's operands:
Certain expressions will treat an expression as a place expression by implicitly borrowing it.
For example, it is possible to compare two unsized [slices][slice] for equality directly, because the `==` operator implicitly borrows it's operands:

```rust
# let c = [1, 2, 3];
Expand All @@ -242,21 +237,19 @@ Implicit borrows may be taken in the following expressions:
* Left operand in [method-call] expressions.
* Left operand in [field] expressions.
* Left operand in [call expressions].
* Left operand in [array indexing] expressions.
* Left operand in [array indexing expressions].
* Operand of the [dereference operator][deref] (`*`).
* Operands of [comparison].
* Left operands of the [compound assignment].

## Overloading Traits

Many of the following operators and expressions can also be overloaded for
other types using traits in `std::ops` or `std::cmp`. These traits also
exist in `core::ops` and `core::cmp` with the same names.
Many of the following operators and expressions can also be overloaded for other types using traits in `std::ops` or `std::cmp`.
These traits also exist in `core::ops` and `core::cmp` with the same names.

## Expression Attributes

[Outer attributes][_OuterAttribute_] before an expression are allowed only in
a few specific cases:
[Outer attributes][_OuterAttribute_] before an expression are allowed only in a few specific cases:

* Before an expression used as a [statement].
* Elements of [array expressions], [tuple expressions], [call expressions],
Expand All @@ -271,9 +264,7 @@ a few specific cases:

They are never allowed before:
* [Range][_RangeExpression_] expressions.
* Binary operator expressions ([_ArithmeticOrLogicalExpression_],
[_ComparisonExpression_], [_LazyBooleanExpression_], [_TypeCastExpression_],
[_AssignmentExpression_], [_CompoundAssignmentExpression_]).
* Binary operator expressions ([_ArithmeticOrLogicalExpression_], [_ComparisonExpression_], [_LazyBooleanExpression_], [_TypeCastExpression_], [_AssignmentExpression_], [_CompoundAssignmentExpression_]).


[block expressions]: expressions/block-expr.md
Expand All @@ -283,13 +274,15 @@ They are never allowed before:
[`if let`]: expressions/if-expr.md#if-let-expressions
[match]: expressions/match-expr.md
[method-call]: expressions/method-call-expr.md
[paren]: expressions/grouped-expr.md
[paths]: expressions/path-expr.md
[struct]: expressions/struct-expr.md
[tuple expressions]: expressions/tuple-expr.md
[tuple indexing expressions]: expressions/tuple-expr.md#tuple-indexing-expressions
[`while let`]: expressions/loop-expr.md#predicate-pattern-loops

[array expressions]: expressions/array-expr.md
[array indexing]: expressions/array-expr.md#array-and-slice-indexing-expressions
[array expressions]: expressions/array-expr.md
[array indexing expressions]: expressions/array-expr.md#array-and-slice-indexing-expressions

[assign]: expressions/operator-expr.md#assignment-expressions
[borrow]: expressions/operator-expr.md#borrow-operators
Expand Down
8 changes: 4 additions & 4 deletions src/expressions/operator-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,20 +435,20 @@ x += 1;
assert!(x == 6);
```

The syntax of compound assignment is a [mutable] [place expression], the *assigned operand*, then one of the operators followed by an `=` as a single token (no whitespace), and then a [value expression], the *modifying operand*.
The syntax of compound assignment is a [mutable] [place expression], the *assigned place operand*, then one of the operators followed by an `=` as a single token (no whitespace), and then a [value expression], the *modifying operand*.

Unlike other place operands, the assigned place operand must be a place expression.
Attempting to use a value expression is a compiler error rather than promoting it to a temporary.

Evaluation of compound assignment expressions depends on the types of the operators.

If both types are primitives, then the modifying operand will be evaluated first followed by the assigned operand.
It will then set the value of the assigned operand's place to the value of performing the operation of the operator with the values of the assigned operand and modifying operand.
If both types are primitives, then the modifying operand will be evaluated first followed by the assigned place operand.
It will then set the value of the assigned place operand's place to the value of performing the operation of the operator with the values of the assigned place operand and modifying operand.

> **Note**: This is different than other expressions in that the right operand is evaluated before the left one.

Otherwise, this expression is syntactic sugar for calling the function of the overloading compound assigment trait of the operator (see the table earlier in this chapter).
A mutable borrow of the assigned operand is automatically taken.
A mutable borrow of the assigned place operand is automatically taken.

For example, the following expression statements in `example` are equivalent:

Expand Down