Suggest removing ;
for ;
within let-chains by sjwang05 · Pull Request #117743 · rust-lang/rust (original) (raw)
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
[ Show hidden characters]({{ revealButtonHref }})
rustbot added S-waiting-on-review
Status: Awaiting review from the assignee but also interested parties.
Relevant to the compiler team, which will review and decide on the PR/issue.
labels
sjwang05 changed the title
Suggest removing ';' for ';' within let-chains Suggest removing ;
for ;
within 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-review
Status: Awaiting review from the assignee but also interested parties.
labels
bors added a commit to rust-lang-ci/rust that referenced this pull request
…iaskrgr
Rollup of 6 pull requests
Successful merges:
- rust-lang#114191 (Update exploit mitigations documentation)
- rust-lang#117039 (Clarify UB in
get_unchecked(_mut)
) - rust-lang#117730 (Closure-consuming helper functions for
fmt::Debug
helpers) - rust-lang#117741 (Fix typo in internal.rs)
- rust-lang#117743 (Suggest removing
;
for;
within let-chains) - rust-lang#117751 (rustdoc-json: Fix test so it actually checks things)
r? @ghost
@rustbot
modify labels: rollup
rust-timer added a commit to rust-lang-ci/rust that referenced this pull request
obeis mentioned this pull request
celinval added a commit to celinval/rust-dev that referenced this pull request
Update Rust toolchain from nightly-2023-11-10 to nightly-2023-11-11
without any other source changes.
This is an automatically generated pull request. If any of the CI checks
fail, manual intervention is required. In such a case, review the
changes at https://github.com/rust-lang/rust from
rust-lang@0f44eb3
up to
rust-lang@edf0b1d.
The log for this commit range is:
rust-lang@edf0b1db0a Auto merge of
rust-lang#115229 - iSwapna:issue-115222-fix, r=estebank
rust-lang@56a109d15b Recurse over the
method chain and maintain a stack to peek at previous receiver to align
spans
rust-lang@d4c86cfc49 Auto merge of
rust-lang#117779 - bjorn3:sync_cg_clif-2023-11-10, r=bjorn3
rust-lang@d186b49460 Merge commit
'c84d1871dc4456539b7b578830268ab3539915d0' into sync_cg_clif-2023-11-10
rust-lang@c84d1871dc Rustup to rustc
1.75.0-nightly (0f44eb3 2023-11-09)
rust-lang@6e7961ac5d Sync from rust
0f44eb3
rust-lang@3d0e99d632 Auto merge of
rust-lang#117765 - onur-ozkan:fix-117762, r=clubby789
rust-lang@17d0a45f5d Auto merge of
rust-lang#117572 - RalfJung:addr_of, r=cuviper
rust-lang@e30f8ae867 mention null
explicitly
rust-lang@0a1e5598b0 Auto merge of
rust-lang#117750 - klensy:icu-followup, r=Nilstrieb
rust-lang@d42d73b144 Auto merge of
rust-lang#117769 - matthiaskrgr:rollup-4efjlg3, r=matthiaskrgr
rust-lang@186a3c8c61 Rollup merge of
rust-lang#117751 - aDotInTheVoid:unkind, r=GuillaumeGomez
rust-lang@7607597d3a Rollup merge of
rust-lang#117743 - sjwang05:issue-117720, r=estebank
rust-lang@7fd7719ca1 Rollup merge of
rust-lang#117741 - eltociear:patch-23, r=compiler-errors
rust-lang@0f1da7e682 Rollup merge of
rust-lang#117730 - jmillikin:fmt-debug-helper-fns, r=cuviper
rust-lang@7096ec3e00 Rollup merge of
rust-lang#117039 - scottmcm:clarify-get-unchecked, r=cuviper
rust-lang@9dc022dd80 Rollup merge of
rust-lang#114191 - rcvalle:rust-exploit-mitigations, r=cuviper
rust-lang@82a9f94de5 Closure-consuming
helper functions for fmt::Debug
helpers
rust-lang@fdb72795d1 enable unstable
feature on x clean [PATH]
rust-lang@22e1576a12 rustdoc-json: Fix
test so it actuall checks things
rust-lang@7142c8d83c bump few ICU4X
leftover deps
rust-lang@5693a34db2 Suggest fix for ;
within let-chains
rust-lang@b8648216a5 Fix typo in
internal.rs
rust-lang@7c385f5a03 Update exploit
mitigations documentation
rust-lang@545175ce87 Fix addition
formatting
rust-lang@82487a9447 Merge pull request
rust-lang#1417 from rust-lang/implement_xgetbv
rust-lang@864973135a Implement all vendor
intrinsics used by the simd-json crate
rust-lang@9f426cef38 Merge pull request
rust-lang#1416 from afonso360/aarch64-intrinsics-1
rust-lang@ecf79a304a Implement all vendor
intrinsics used by the fimg crate
rust-lang@0a35232c85 Implement all vendor
intrinsics used by the httparse crate
rust-lang@61e38ceea7 Implement all SSE
intrinsics used by the jpeg-decoder crate
rust-lang@438194980b Implement all avx2
intrinsics used by the image crate
rust-lang@6a53acefd8 Implement
_mm256_permute2f128_ps and _mm256_permute2f128_pd intrinsics
rust-lang@81af5b5031 update and clarify
addr_of docs
rust-lang@209476e33a Only import aarch64
intrinsics on aarch64
rust-lang@f824da66c6 Make neon example
build in all arches
rust-lang@70a6abfd29 Add unsigned
saturating add/sub intrinsics for aarch64
rust-lang@88c2e7896b Implement aarch64
addp intrinsics
rust-lang@1f09bae6a8 Implement min/max
neon intrisics
rust-lang@8eca01f4b6 Remove support for
compiler plugins.
rust-lang@f6a8c3afb5 Add real
implementation of _xgetbv()
rust-lang@909513ef74 Use Value instead of
CValue in CInlineAsmOperand
rust-lang@ef3703694f Disable a couple of
rustc tests which are broken due to a rustc bug
rust-lang@c04ceb4342 Fix workaround for
the int <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow></mrow><annotation encoding="application/x-tex"></annotation></semantics></math></span><span class="katex-html" aria-hidden="true"></span></span>0x29
issue to not crash on empty inline asm
rust-lang@04f1024ecb Rustup to rustc
1.75.0-nightly (75b064d 2023-11-01)
rust-lang@361585e06d Sync from rust
75b064d
rust-lang@03c9acdd8f Support enum
variants in offset_of!
rust-lang@48ca2d9703 Implement
llvm.fma.v* intrinsics
rust-lang@aed0ed2875 Rollup merge of
rust-lang#117317 - RalfJung:track-caller, r=oli-obk
rust-lang@9a33f82140 Remove inline asm
support from the list of limitations
rust-lang@51f6ac7bfc Merge branch
'sync_from_rust'
rust-lang@41dcb52153 Merge commit
'dde58803fd6cbb270c7a437f36a8a3a29fbef679' into sync_cg_clif-2023-10-29
rust-lang@c6f5090294 share the
track_caller handling within a mir::Body
rust-lang@bad4be6e29 interpret: call
caller_location logic the same way codegen does, and share some code
rust-lang@01ca7a0cb0 Add the missing word
rust-lang@2c13ee8970 Clarify UB in
get_unchecked(_mut)
rust-lang@40a83be6eb Format exploit
mitigations documentation
Co-authored-by: celinval celinval@users.noreply.github.com
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.
github-actions bot pushed a commit to rust-lang/miri 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 #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/rust#103293 (comment)
[drop order changes]: rust-lang/rust#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/rust#94927
- rust-lang/rust#94951
- rust-lang/rust#94974
- rust-lang/rust#95008
- rust-lang/rust#97295
- rust-lang/rust#98633
- rust-lang/rust#99731
- rust-lang/rust#102394
- rust-lang/rust#100526
- rust-lang/rust#100538
- rust-lang/rust#102998
- rust-lang/rust#103405
- rust-lang/rust#103293
- rust-lang/rust#107251
- rust-lang/rust#110568
- rust-lang/rust#115677
- rust-lang/rust#117743
- rust-lang/rust#117770
- rust-lang/rust#118191
- rust-lang/rust#119554
- rust-lang/rust#129394
- rust-lang/rust#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/rust#115983
- rust-lang/rust#116549
- rust-lang/rust#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 #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 #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): #117977 - An instance where a temporary lives shorter than with nested ifs, breaking compilation: #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 #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/rust#132828
- Style: rust-lang/rust#139456
- rust-lang/rust#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.
github-actions bot pushed a commit to rust-lang/rustc-dev-guide 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 #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/rust#103293 (comment)
[drop order changes]: rust-lang/rust#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/rust#94927
- rust-lang/rust#94951
- rust-lang/rust#94974
- rust-lang/rust#95008
- rust-lang/rust#97295
- rust-lang/rust#98633
- rust-lang/rust#99731
- rust-lang/rust#102394
- rust-lang/rust#100526
- rust-lang/rust#100538
- rust-lang/rust#102998
- rust-lang/rust#103405
- rust-lang/rust#103293
- rust-lang/rust#107251
- rust-lang/rust#110568
- rust-lang/rust#115677
- rust-lang/rust#117743
- rust-lang/rust#117770
- rust-lang/rust#118191
- rust-lang/rust#119554
- rust-lang/rust#129394
- rust-lang/rust#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/rust#115983
- rust-lang/rust#116549
- rust-lang/rust#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 #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 #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): #117977 - An instance where a temporary lives shorter than with nested ifs, breaking compilation: #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 #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/rust#132828
- Style: rust-lang/rust#139456
- rust-lang/rust#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.