Formally implement let chains by c410-f3r · Pull Request #88642 · rust-lang/rust (original) (raw)
rustbot added S-waiting-on-author
Status: This is awaiting some action (such as code changes or more information) from the author.
and removed S-waiting-on-review
Status: Awaiting review from the assignee but also interested parties.
labels
apiraino added the T-compiler
Relevant to the compiler team, which will review and decide on the PR/issue.
label
JohnCSimon added S-waiting-on-author
Status: This is awaiting some action (such as code changes or more information) from the author.
and removed S-waiting-on-author
Status: This is awaiting some action (such as code changes or more information) from the author.
labels
c410-f3r changed the title
[WIP] Formally implement let chains Formally implement let chains
bors added S-waiting-on-bors
Status: Waiting on bors to run and complete tests. Bors will change the label on completion.
and removed S-waiting-on-author
Status: This is awaiting some action (such as code changes or more information) from the author.
labels
bors added a commit to rust-lang-ci/rust that referenced this pull request
…askrgr
Rollup of 10 pull requests
Successful merges:
- rust-lang#88642 (Formally implement let chains)
- rust-lang#89621 (doc: guarantee call order for sort_by_cached_key)
- rust-lang#91278 (Use iterator instead of recursion in
codegen_place
) - rust-lang#92124 (Little improves in CString
new
when creating from slice) - rust-lang#92783 (Annotate dead code lint with notes about ignored derived impls)
- rust-lang#92797 (Remove horizontal lines at top of page)
- rust-lang#92920 (Move expr- and item-related pretty printing functions to modules)
- rust-lang#93041 (Remove some unused ordering derivations based on
DefId
) - rust-lang#93051 (Add Option::is_some_with and Result::is_{ok,err}_with)
- rust-lang#93062 (Update books)
Failed merges:
r? @ghost
@rustbot
modify labels: rollup
This was referenced
Jan 19, 2022
ehuss mentioned this pull request
15 tasks
JohnTitor added a commit to JohnTitor/rust that referenced this pull request
…shtriplett
Stabilize let_chains
in Rust 1.64
Stabilization proposal
This PR proposes the stabilization of #![feature(let_chains)]
in a future-compatibility way that will allow the possible addition of the EXPR is PAT
syntax.
Tracking issue: rust-lang#53667 Version: 1.64 (beta => 2022-08-11, stable => 2022-10-22).
What is stabilized
The ability to chain let expressions along side local variable declarations or ordinary conditional expressions. For example:
pub enum Color {
Blue,
Red,
Violet,
}
pub enum Flower {
Rose,
Tulip,
Violet,
}
pub fn roses_are_red_violets_are_blue_printer(
(first_flower, first_flower_color): (Flower, Color),
(second_flower, second_flower_color): (Flower, Color),
pick_up_lines: &[&str],
) {
if let Flower::Rose = first_flower
&& let Color::Red = first_flower_color
&& let Flower::Violet = second_flower
&& let Color::Blue = second_flower_color
&& let &[first_pick_up_line, ..] = pick_up_lines
{
println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
}
fn main() {
roses_are_red_violets_are_blue_printer(
(Flower::Rose, Color::Red),
(Flower::Violet, Color::Blue),
&["sugar is sweet and so are you"],
);
}
Motivation
The main motivation for this feature is improving readability, ergonomics and reducing paper cuts.
For more examples, see the RFC.
What isn't stabilized
Let chains in match guards (
if_let_guard
)Resolution of divergent non-terminal matchers
The
EXPR is PAT
syntax
History
- On 2017-12-24, RFC: if- and while-let-chains
- On 2018-07-12, eRFC: if- and while-let-chains, take 2
- On 2018-08-24, Tracking issue for eRFC 2497, "if- and while-let-chains, take 2
- On 2019-03-19, Run branch cleanup after copy prop
- On 2019-03-26, Generalize diagnostic for x = y where bool is the expected type
- On 2019-04-24, Introduce hir::ExprKind::Use and employ in for loop desugaring
- On 2019-03-19, [let_chains, 1/6] Remove hir::ExprKind::If
- On 2019-05-15, [let_chains, 2/6] Introduce Let(..) in AST, remove IfLet + WhileLet and parse let chains
- On 2019-06-20, [let_chains, 3/6] And then there was only Loop
- On 2020-11-22, Reintroduce hir::ExprKind::If
- On 2020-12-24, Introduce hir::ExprKind::Let - Take 2
- On 2021-02-19, Lower condition of if expression before it's "then" block
- On 2021-09-01, Fix drop handling for
if let
expressions - On 2021-09-04, Formally implement let chains
- On 2022-01-19, Add tests to ensure that let_chains works with if_let_guard
- On 2022-01-18, Introduce
enhanced_binary_op
feature - On 2022-01-22, Fix
let_chains
andif_let_guard
feature flags - On 2022-02-25, Initiate the inner usage of
let_chains
- On 2022-01-28, [WIP] Introduce ast::StmtKind::LetElse to allow the usage of
let_else
withlet_chains
- On 2022-02-26, 1 - Make more use of
let_chains
- On 2022-02-26, 2 - Make more use of
let_chains
- On 2022-02-27, 3 - Make more use of
let_chains
- On 2022-02-28, 4 - Make more use of
let_chains
- On 2022-02-28, 5 - Make more use of
let_chains
- On 2022-02-28, 6 - Make more use of
let_chains
- On 2022-03-01, 7 - Make more use of
let_chains
- On 2022-03-01, 8 - Make more use of
let_chains
- On 2022-03-01, 9 - Make more use of
let_chains
- On 2022-03-08, Warn users about
||
in let chain expressions
From the first RFC (2017-12-24) to the theoretical future stabilization day (2022-10-22), it can be said that this feature took 4 years, 9 months and 28 days of research, development, discussions, agreements and headaches to be settled.
Divergent non-terminal matchers
More specifically, rust-lang#86730.
macro_rules! mac {
($e:expr) => {
if $e {
true
} else {
false
}
};
}
fn main() {
// OK!
assert_eq!(mac!(true && let 1 = 1), true);
// ERROR! Anything starting with `let` is not considered an expression
assert_eq!(mac!(let 1 = 1 && true), true);
}
To the best of my knowledge, such error or divergence is orthogonal, does not prevent stabilization and can be tackled independently in the near future or effectively in the next Rust 2024 edition. If not, then https://github.com/c410-f3r/rust/tree/let-macro-blah contains a set of changes that will consider let
an expression.
It is possible that none of the solutions above satisfies all applicable constraints but I personally don't know of any other plausible answers.
Alternative syntax
Taking into account the usefulness of this feature and the overwhelming desire to use both now and in the past, let PAT = EXPR
will be utilized for stabilization but it doesn't or shall create any obstacle for a possible future addition of EXPR is PAT
.
The introductory snippet would then be written as the following.
if first_flower is Flower::Rose
&& first_flower_color is Color::Red
&& second_flower is Flower::Violet
&& second_flower_color is Color::Blue
&& pick_up_lines is &[first_pick_up_line, ..]
{
println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
Just to reinforce, this PR only unblocks a possible future road for EXPR is PAT
and does emphasize what is better or what is worse.
Tests
AST lowering does not wrap let chains in an
DropTemps
expressionA collection of statements where
let
expressions are forbiddenAll or at least most of the places where let chains are allowed
issue-88498.rs, issue-90722.rs, issue-92145.rs and issue-93150.rs were bugs found by third parties and fixed overtime.
Indexing was triggering a ICE due to a wrongly constructed MIR graph
Most of the infra-structure used by let chains is also used by if
expressions in stable compiler versions since rust-lang#80357 and rust-lang#88572. As a result, no bugs were found since the integration of rust-lang#88642.
Possible future work
Let chains in match guards is implemented and working but stabilization is blocked by
if_let_guard
.The usage of
let_chains
withlet_else
is possible but not implemented. Regardless, one attempt was introduced and closed in rust-lang#93437.
Thanks @Centril
for creating the RFC and huge thanks (again) to @matthewjasper
for all the reviews, mentoring and MIR implementations.
Fixes rust-lang#53667
workingjubilee pushed a commit to tcdi/postgrestd that referenced this pull request
Stabilize let_chains
in Rust 1.64
Stabilization proposal
This PR proposes the stabilization of #![feature(let_chains)]
in a future-compatibility way that will allow the possible addition of the EXPR is PAT
syntax.
Tracking issue: #53667 Version: 1.64 (beta => 2022-08-11, stable => 2022-10-22).
What is stabilized
The ability to chain let expressions along side local variable declarations or ordinary conditional expressions. For example:
pub enum Color {
Blue,
Red,
Violet,
}
pub enum Flower {
Rose,
Tulip,
Violet,
}
pub fn roses_are_red_violets_are_blue_printer(
(first_flower, first_flower_color): (Flower, Color),
(second_flower, second_flower_color): (Flower, Color),
pick_up_lines: &[&str],
) {
if let Flower::Rose = first_flower
&& let Color::Red = first_flower_color
&& let Flower::Violet = second_flower
&& let Color::Blue = second_flower_color
&& let &[first_pick_up_line, ..] = pick_up_lines
{
println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
}
fn main() {
roses_are_red_violets_are_blue_printer(
(Flower::Rose, Color::Red),
(Flower::Violet, Color::Blue),
&["sugar is sweet and so are you"],
);
}
Motivation
The main motivation for this feature is improving readability, ergonomics and reducing paper cuts.
For more examples, see the RFC.
What isn't stabilized
Let chains in match guards (
if_let_guard
)Resolution of divergent non-terminal matchers
The
EXPR is PAT
syntax
History
- On 2017-12-24, RFC: if- and while-let-chains
- On 2018-07-12, eRFC: if- and while-let-chains, take 2
- On 2018-08-24, Tracking issue for eRFC 2497, "if- and while-let-chains, take 2
- On 2019-03-19, Run branch cleanup after copy prop
- On 2019-03-26, Generalize diagnostic for x = y where bool is the expected type
- On 2019-04-24, Introduce hir::ExprKind::Use and employ in for loop desugaring
- On 2019-03-19, [let_chains, 1/6] Remove hir::ExprKind::If
- On 2019-05-15, [let_chains, 2/6] Introduce Let(..) in AST, remove IfLet + WhileLet and parse let chains
- On 2019-06-20, [let_chains, 3/6] And then there was only Loop
- On 2020-11-22, Reintroduce hir::ExprKind::If
- On 2020-12-24, Introduce hir::ExprKind::Let - Take 2
- On 2021-02-19, Lower condition of if expression before it's "then" block
- On 2021-09-01, Fix drop handling for
if let
expressions - On 2021-09-04, Formally implement let chains
- On 2022-01-19, Add tests to ensure that let_chains works with if_let_guard
- On 2022-01-18, Introduce
enhanced_binary_op
feature - On 2022-01-22, Fix
let_chains
andif_let_guard
feature flags - On 2022-02-25, Initiate the inner usage of
let_chains
- On 2022-01-28, [WIP] Introduce ast::StmtKind::LetElse to allow the usage of
let_else
withlet_chains
- On 2022-02-26, 1 - Make more use of
let_chains
- On 2022-02-26, 2 - Make more use of
let_chains
- On 2022-02-27, 3 - Make more use of
let_chains
- On 2022-02-28, 4 - Make more use of
let_chains
- On 2022-02-28, 5 - Make more use of
let_chains
- On 2022-02-28, 6 - Make more use of
let_chains
- On 2022-03-01, 7 - Make more use of
let_chains
- On 2022-03-01, 8 - Make more use of
let_chains
- On 2022-03-01, 9 - Make more use of
let_chains
- On 2022-03-08, Warn users about
||
in let chain expressions
From the first RFC (2017-12-24) to the theoretical future stabilization day (2022-10-22), it can be said that this feature took 4 years, 9 months and 28 days of research, development, discussions, agreements and headaches to be settled.
Divergent non-terminal matchers
More specifically, rust-lang/rust#86730.
macro_rules! mac {
($e:expr) => {
if $e {
true
} else {
false
}
};
}
fn main() {
// OK!
assert_eq!(mac!(true && let 1 = 1), true);
// ERROR! Anything starting with `let` is not considered an expression
assert_eq!(mac!(let 1 = 1 && true), true);
}
To the best of my knowledge, such error or divergence is orthogonal, does not prevent stabilization and can be tackled independently in the near future or effectively in the next Rust 2024 edition. If not, then https://github.com/c410-f3r/rust/tree/let-macro-blah contains a set of changes that will consider let
an expression.
It is possible that none of the solutions above satisfies all applicable constraints but I personally don't know of any other plausible answers.
Alternative syntax
Taking into account the usefulness of this feature and the overwhelming desire to use both now and in the past, let PAT = EXPR
will be utilized for stabilization but it doesn't or shall create any obstacle for a possible future addition of EXPR is PAT
.
The introductory snippet would then be written as the following.
if first_flower is Flower::Rose
&& first_flower_color is Color::Red
&& second_flower is Flower::Violet
&& second_flower_color is Color::Blue
&& pick_up_lines is &[first_pick_up_line, ..]
{
println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
Just to reinforce, this PR only unblocks a possible future road for EXPR is PAT
and does emphasize what is better or what is worse.
Tests
AST lowering does not wrap let chains in an
DropTemps
expressionA collection of statements where
let
expressions are forbiddenAll or at least most of the places where let chains are allowed
issue-88498.rs, issue-90722.rs, issue-92145.rs and issue-93150.rs were bugs found by third parties and fixed overtime.
Indexing was triggering a ICE due to a wrongly constructed MIR graph
Most of the infra-structure used by let chains is also used by if
expressions in stable compiler versions since rust-lang/rust#80357 and rust-lang/rust#88572. As a result, no bugs were found since the integration of rust-lang/rust#88642.
Possible future work
Let chains in match guards is implemented and working but stabilization is blocked by
if_let_guard
.The usage of
let_chains
withlet_else
is possible but not implemented. Regardless, one attempt was introduced and closed in rust-lang/rust#93437.
Thanks @Centril
for creating the RFC and huge thanks (again) to @matthewjasper
for all the reviews, mentoring and MIR implementations.
Fixes #53667
est31 mentioned this pull request
9 tasks
bors added a commit to rust-lang-ci/rust that referenced this pull request
Stabilize let chains in the 2024 edition
Stabilization report
This proposes the stabilization of let_chains
(tracking issue, RFC 2497) in the 2024 edition of Rust.
What is being stabilized
The ability to &&
-chain let
statements inside if
and while
is being stabilized, allowing intermixture with boolean expressions. The patterns inside the let
sub-expressions can be irrefutable or refutable.
struct FnCall<'a> {
fn_name: &'a str,
args: Vec<i32>,
}
fn is_legal_ident(s: &str) -> bool {
s.chars()
.all(|c| ('a'..='z').contains(&c) || ('A'..='Z').contains(&c))
}
impl<'a> FnCall<'a> {
fn parse(s: &'a str) -> Option<Self> {
if let Some((fn_name, after_name)) = s.split_once("(")
&& !fn_name.is_empty()
&& is_legal_ident(fn_name)
&& let Some((args_str, "")) = after_name.rsplit_once(")")
{
let args = args_str
.split(',')
.map(|arg| arg.parse())
.collect::<Result<Vec<_>, _>>();
args.ok().map(|args| FnCall { fn_name, args })
} else {
None
}
}
fn exec(&self) -> Option<i32> {
let iter = self.args.iter().copied();
match self.fn_name {
"sum" => Some(iter.sum()),
"max" => iter.max(),
"min" => iter.min(),
_ => None,
}
}
}
fn main() {
println!("{:?}", FnCall::parse("sum(1,2,3)").unwrap().exec());
println!("{:?}", FnCall::parse("max(4,5)").unwrap().exec());
}
The feature will only be stabilized for the 2024 edition and future editions. Users of past editions will get an error with a hint to update the edition.
closes rust-lang#53667
Why 2024 edition?
Rust generally tries to ship new features to all editions. So even the oldest editions receive the newest features. However, sometimes a feature requires a breaking change so much that offering the feature without the breaking change makes no sense. This occurs rarely, but has happened in the 2018 edition already with async
and await
syntax. It required an edition boundary in order for async
/await
to become keywords, and the entire feature foots on those keywords.
In the instance of let chains, the issue is the drop order of if let
chains. If we want if let
chains to be compatible with if let
, drop order makes it hard for us to generate correct MIR. It would be strange to have different behaviour for if let ... {}
and if true && let ... {}
. So it's better to [stay consistent with if let
].
In edition 2024, [drop order changes] have been introduced to make if let
temporaries be lived more shortly. These changes also affected if let
chains. These changes make sense even if you don't take the if let
chains MIR generation problem into account. But if we want to use them as the solution to the MIR generation problem, we need to restrict let chains to edition 2024 and beyond: for let chains, it's not just a change towards more sensible behaviour, but one required for correct function.
[stay consistent with if let
]: rust-lang#103293 (comment)
[drop order changes]: rust-lang#124085
Introduction considerations
As edition 2024 is very new, this stabilization PR only makes it possible to use let chains on 2024 without that feature gate, it doesn't mark that feature gate as stable/removed. I would propose to continue offering the let_chains
feature (behind a feature gate) for a limited time (maybe 3 months after stabilization?) on older editions to allow nightly users to adopt edition 2024 at their own pace. After that, the feature gate shall be marked as stabilized, not removed, and replaced by an error on editions 2021 and below.
Implementation history
- History from before March 14, 2022 can be found in the original stabilization PR that was reverted.
- rust-lang#94927
- rust-lang#94951
- rust-lang#94974
- rust-lang#95008
- rust-lang#97295
- rust-lang#98633
- rust-lang#99731
- rust-lang#102394
- rust-lang#100526
- rust-lang#100538
- rust-lang#102998
- rust-lang#103405
- rust-lang#103293
- rust-lang#107251
- rust-lang#110568
- rust-lang#115677
- rust-lang#117743
- rust-lang#117770
- rust-lang#118191
- rust-lang#119554
- rust-lang#129394
- rust-lang#132828
- rust-lang/reference#1179
- rust-lang/reference#1251
- rust-lang/rustfmt#5910
Adoption history
In the compiler
- History before March 14, 2022 can be found in the original stabilization PR.
- rust-lang#115983
- rust-lang#116549
- rust-lang#116688
Outside of the compiler
Tests
Intentional restrictions
partially-macro-expanded.rs
, macro-expanded.rs
: it is possible to use macros to expand to both the pattern and the expression inside a let chain, but not to the entire let pat = expr
operand.
parens.rs
: if (let pat = expr)
is not allowed in chains
ensure-that-let-else-does-not-interact-with-let-chains.rs
: let...else
doesn't support chaining.
Overlap with match guards
move-guard-if-let-chain.rs
: test for the use moved value
error working well in match guards. could maybe be extended with let chains that have more than one let
shadowing.rs
: shadowing in if let guards works as expected
ast-validate-guards.rs
: let chains in match guards require the match guards feature gate
Simple cases from the early days
PR rust-lang#88642 has added some tests with very simple usages of let else
, mostly as regression tests to early bugs.
then-else-blocks.rs
ast-lowering-does-not-wrap-let-chains.rs
issue-90722.rs
issue-92145.rs
Drop order/MIR scoping tests
issue-100276.rs
: let expressions on RHS aren't terminating scopes
drop_order.rs
: exhaustive temporary drop order test for various Rust constructs, including let chains
scope.rs
: match guard scoping test
drop-scope.rs
: another match guard scoping test, ensuring that temporaries in if-let guards live for the arm
drop_order_if_let_rescope.rs
: if let rescoping on edition 2024, including chains
mir_let_chains_drop_order.rs
: comprehensive drop order test for let chains, distinguishes editions 2021 and 2024.
issue-99938.rs
, issue-99852.rs
both bad MIR ICEs fixed by rust-lang#102394
Linting
irrefutable-lets.rs
: trailing and leading irrefutable let patterns get linted for, others don't. The lint is turned off for else if
.
issue-121070-let-range.rs
: regression test for false positive of the unused parens lint, precedence requires the ()
s here
Parser: intentional restrictions
disallowed-positions.rs
: let
in expression context is rejected everywhere except at the top level
invalid-let-in-a-valid-let-context.rs
: nested let
is not allowed (let's are no legal expressions just because they are allowed in if
and while
).
Parser: recovery
issue-103381.rs
: Graceful recovery of incorrect chaining of if
and if let
semi-in-let-chain.rs
: Ensure that stray ;
s in let chains give nice errors (if_chain!
users might be accustomed to ;
s)
deli-ident-issue-1.rs
, brace-in-let-chain.rs
: Ensure that stray unclosed {
s in let chains give nice errors and hints
Misc
conflicting_bindings.rs
: the conflicting bindings check also works in let chains. Personally, I'd extend it to chains with multiple let's as well.
let-chains-attr.rs
: attributes work on let chains
Tangential tests with #![feature(let_chains)]
if-let.rs
: MC/DC coverage tests for let chains
logical_or_in_conditional.rs
: not really about let chains, more about dropping/scoping behaviour of ||
stringify.rs
: exhaustive test of the stringify
macro
expanded-interpolation.rs
, expanded-exhaustive.rs
: Exhaustive test of -Zunpretty
diverges-not.rs
: Never type, mostly tangential to let chains
Possible future work
- There is proposals to allow
if let Pat(bindings) = expr {}
to be written asif expr is Pat(bindings) {}
(RFC 3573).if let
chains are a natural extension of the already existingif let
syntax, and I'd argue orthogonal towardsis
syntax. - One could have similar chaining inside
let ... else
statements. There is no proposed RFC for this however, nor is it implemented on nightly. - Match guards have the
if
keyword as well, but on stable Rust, they don't supportlet
. The functionality is available via an unstable feature (if_let_guard
tracking issue). Stabilization of let chains affects this feature in so far as match guards containing let chains now only need theif_let_guard
feature gate be present instead of also thelet_chains
feature (NOTE: this PR doesn't implement this simplification, it's left for future work).
Open questions / blockers
- bad recovery if you don't put a
let
(I don't think this is a blocker): rust-lang#117977 - An instance where a temporary lives shorter than with nested ifs, breaking compilation: rust-lang#103476. Personally I don't think this is a blocker either, as it's an edge case. Edit: turns out to not reproduce in edition 2025 any more, due to let rescoping. regression test added in rust-lang#133093
- One should probably extend the tests for
move-guard-if-let-chain.rs
andconflicting_bindings.rs
to have chains with multiple let's: done in 133093 - Parsing rejection tests: addressed by rust-lang#132828
- Style: rust-lang#139456
- rust-lang#86730 explicitly mentions
let_else
. I think we can live withlet pat = expr
not evaluating asexpr
for macro_rules macros, especially given thatlet pat = expr
is not a legal expression anywhere except insideif
andwhile
. - Documentation in the reference: rust-lang/reference#1740
- Add chapter to the Rust 2024 edition guide: rust-lang/edition-guide#337
- Resolve open questions on desired drop order.