Skip to content

Commit 8bf5a8d

Browse files
committed
Auto merge of rust-lang#132833 - est31:stabilize_let_chains, r=fee1-dead
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. [tracking issue]: rust-lang#53667 [RFC 2497]: rust-lang/rfcs#2497 [2024 edition]: https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html ## 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. ```Rust 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. [generate correct MIR]: rust-lang#104843 [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 [original stabilization PR]: rust-lang#94927 ## 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 * rust-lang/rust-clippy#11750 * [rspack](https://github.com/web-infra-dev/rspack) * [risingwave](https://github.com/risingwavelabs/risingwave) * [dylint](https://github.com/trailofbits/dylint) * [convex-backend](https://github.com/get-convex/convex-backend) * [tikv](https://github.com/tikv/tikv) * [Daft](https://github.com/Eventual-Inc/Daft) * [greptimedb](https://github.com/GreptimeTeam/greptimedb) ## Tests <details> ### Intentional restrictions [`partially-macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/partially-macro-expanded.rs), [`macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs): `if (let pat = expr)` is not allowed in chains [`ensure-that-let-else-does-not-interact-with-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/shadowing.rs): shadowing in if let guards works as expected [`ast-validate-guards.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/then-else-blocks.rs) [`ast-lowering-does-not-wrap-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs) [`issue-90722.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-90722.rs) [`issue-92145.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-92145.rs) ### Drop order/MIR scoping tests [`issue-100276.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/issue-100276.rs): let expressions on RHS aren't terminating scopes [`drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order.rs): exhaustive temporary drop order test for various Rust constructs, including let chains [`scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/scope.rs): match guard scoping test [`drop-scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order_if_let_rescope.rs): if let rescoping on edition 2024, including chains [`mir_let_chains_drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/mir_let_chains_drop_order.rs): comprehensive drop order test for let chains, distinguishes editions 2021 and 2024. [`issue-99938.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs), [`issue-99852.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/issue-99852.rs) both bad MIR ICEs fixed by rust-lang#102394 ### Linting [`irrefutable-lets.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/lint/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`](https://github.com/rust-lang/rust/blob/2128d8df0e858edcbe6a0861bac948b88b7fabc3/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs): `let` in expression context is rejected everywhere except at the top level [`invalid-let-in-a-valid-let-context.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/issues/issue-103381.rs): Graceful recovery of incorrect chaining of `if` and `if let` [`semi-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/deli-ident-issue-1.rs), [`brace-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/brace-in-let-chain.rs): Ensure that stray unclosed `{`s in let chains give nice errors and hints ### Misc [`conflicting_bindings.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/pattern/usefulness/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/expr/if/attrs/let-chains-attr.rs): attributes work on let chains ### Tangential tests with `#![feature(let_chains)]` [`if-let.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/coverage/branch/if-let.rs): MC/DC coverage tests for let chains [`logical_or_in_conditional.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/mir-opt/building/logical_or_in_conditional.rs): not really about let chains, more about dropping/scoping behaviour of `||` [`stringify.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/macros/stringify.rs): exhaustive test of the `stringify` macro [`expanded-interpolation.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-interpolation.rs), [`expanded-exhaustive.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-exhaustive.rs): Exhaustive test of `-Zunpretty` [`diverges-not.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-0000-never_patterns/diverges-not.rs): Never type, mostly tangential to let chains </details> ## Possible future work * There is proposals to allow `if let Pat(bindings) = expr {}` to be written as `if expr is Pat(bindings) {}` ([RFC 3573]). `if let` chains are a natural extension of the already existing `if let` syntax, and I'd argue orthogonal towards `is` syntax. * rust-lang/lang-team#297 * 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 support `let`. 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 the `if_let_guard` feature gate be present instead of also the `let_chains` feature (NOTE: this PR doesn't implement this simplification, it's left for future work). [RFC 3573]: rust-lang/rfcs#3573 [`if_let_guard` tracking issue]: rust-lang#51114 ## Open questions / blockers - [ ] bad recovery if you don't put a `let` (I don't think this is a blocker): [rust-lang#117977](rust-lang#117977) - [x] An instance where a temporary lives shorter than with nested ifs, breaking compilation: [rust-lang#103476](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 - [x] One should probably extend the tests for `move-guard-if-let-chain.rs` and `conflicting_bindings.rs` to have chains with multiple let's: done in 133093 - [x] Parsing rejection tests: addressed by rust-lang#132828 - [x] [Style](https://rust-lang.zulipchat.com/#narrow/channel/346005-t-style/topic/let.20chains.20stabilization.20and.20formatting): rust-lang#139456 - [x] rust-lang#86730 explicitly mentions `let_else`. I think we can live with `let pat = expr` not evaluating as `expr` for macro_rules macros, especially given that `let pat = expr` is not a legal expression anywhere except inside `if` and `while`. - [x] Documentation in the reference: rust-lang/reference#1740 - [x] Add chapter to the Rust 2024 [edition guide]: rust-lang/edition-guide#337 - [x] Resolve open questions on desired drop order. [original reference PR]: rust-lang/reference#1179 [edition guide]: https://github.com/rust-lang/edition-guide
2 parents 9bfa31f + 5258cb7 commit 8bf5a8d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+411
-184
lines changed

Diff for: compiler/rustc_parse/src/parser/expr.rs

+54-29
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use rustc_macros::Subdiagnostic;
2626
use rustc_session::errors::{ExprParenthesesNeeded, report_lit_error};
2727
use rustc_session::lint::BuiltinLintDiag;
2828
use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
29+
use rustc_span::edition::Edition;
2930
use rustc_span::source_map::{self, Spanned};
3031
use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Symbol, kw, sym};
3132
use thin_vec::{ThinVec, thin_vec};
@@ -2602,7 +2603,10 @@ impl<'a> Parser<'a> {
26022603
/// Parses an `if` expression (`if` token already eaten).
26032604
fn parse_expr_if(&mut self) -> PResult<'a, P<Expr>> {
26042605
let lo = self.prev_token.span;
2605-
let cond = self.parse_expr_cond()?;
2606+
// Scoping code checks the top level edition of the `if`; let's match it here.
2607+
// The `CondChecker` also checks the edition of the `let` itself, just to make sure.
2608+
let let_chains_policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
2609+
let cond = self.parse_expr_cond(let_chains_policy)?;
26062610
self.parse_if_after_cond(lo, cond)
26072611
}
26082612

@@ -2711,18 +2715,17 @@ impl<'a> Parser<'a> {
27112715
}
27122716

27132717
/// Parses the condition of a `if` or `while` expression.
2718+
///
2719+
/// The specified `edition` in `let_chains_policy` should be that of the whole `if` construct,
2720+
/// i.e. the same span we use to later decide whether the drop behaviour should be that of
2721+
/// edition `..=2021` or that of `2024..`.
27142722
// Public because it is used in rustfmt forks such as https://github.com/tucant/rustfmt/blob/30c83df9e1db10007bdd16dafce8a86b404329b2/src/parse/macros/html.rs#L57 for custom if expressions.
2715-
pub fn parse_expr_cond(&mut self) -> PResult<'a, P<Expr>> {
2723+
pub fn parse_expr_cond(&mut self, let_chains_policy: LetChainsPolicy) -> PResult<'a, P<Expr>> {
27162724
let attrs = self.parse_outer_attributes()?;
27172725
let (mut cond, _) =
27182726
self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?;
27192727

2720-
CondChecker::new(self).visit_expr(&mut cond);
2721-
2722-
if let ExprKind::Let(_, _, _, Recovered::No) = cond.kind {
2723-
// Remove the last feature gating of a `let` expression since it's stable.
2724-
self.psess.gated_spans.ungate_last(sym::let_chains, cond.span);
2725-
}
2728+
CondChecker::new(self, let_chains_policy).visit_expr(&mut cond);
27262729

27272730
Ok(cond)
27282731
}
@@ -3017,7 +3020,8 @@ impl<'a> Parser<'a> {
30173020

30183021
/// Parses a `while` or `while let` expression (`while` token already eaten).
30193022
fn parse_expr_while(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
3020-
let cond = self.parse_expr_cond().map_err(|mut err| {
3023+
let policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
3024+
let cond = self.parse_expr_cond(policy).map_err(|mut err| {
30213025
err.span_label(lo, "while parsing the condition of this `while` expression");
30223026
err
30233027
})?;
@@ -3401,17 +3405,17 @@ impl<'a> Parser<'a> {
34013405
}
34023406

34033407
fn parse_match_arm_guard(&mut self) -> PResult<'a, Option<P<Expr>>> {
3404-
// Used to check the `let_chains` and `if_let_guard` features mostly by scanning
3408+
// Used to check the `if_let_guard` feature mostly by scanning
34053409
// `&&` tokens.
3406-
fn check_let_expr(expr: &Expr) -> (bool, bool) {
3410+
fn has_let_expr(expr: &Expr) -> bool {
34073411
match &expr.kind {
34083412
ExprKind::Binary(BinOp { node: BinOpKind::And, .. }, lhs, rhs) => {
3409-
let lhs_rslt = check_let_expr(lhs);
3410-
let rhs_rslt = check_let_expr(rhs);
3411-
(lhs_rslt.0 || rhs_rslt.0, false)
3413+
let lhs_rslt = has_let_expr(lhs);
3414+
let rhs_rslt = has_let_expr(rhs);
3415+
lhs_rslt || rhs_rslt
34123416
}
3413-
ExprKind::Let(..) => (true, true),
3414-
_ => (false, true),
3417+
ExprKind::Let(..) => true,
3418+
_ => false,
34153419
}
34163420
}
34173421
if !self.eat_keyword(exp!(If)) {
@@ -3422,14 +3426,9 @@ impl<'a> Parser<'a> {
34223426
let if_span = self.prev_token.span;
34233427
let mut cond = self.parse_match_guard_condition()?;
34243428

3425-
CondChecker::new(self).visit_expr(&mut cond);
3429+
CondChecker::new(self, LetChainsPolicy::AlwaysAllowed).visit_expr(&mut cond);
34263430

3427-
let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
3428-
if has_let_expr {
3429-
if does_not_have_bin_op {
3430-
// Remove the last feature gating of a `let` expression since it's stable.
3431-
self.psess.gated_spans.ungate_last(sym::let_chains, cond.span);
3432-
}
3431+
if has_let_expr(&cond) {
34333432
let span = if_span.to(cond.span);
34343433
self.psess.gated_spans.gate(sym::if_let_guard, span);
34353434
}
@@ -3456,7 +3455,7 @@ impl<'a> Parser<'a> {
34563455
unreachable!()
34573456
};
34583457
self.psess.gated_spans.ungate_last(sym::guard_patterns, cond.span);
3459-
CondChecker::new(self).visit_expr(&mut cond);
3458+
CondChecker::new(self, LetChainsPolicy::AlwaysAllowed).visit_expr(&mut cond);
34603459
let right = self.prev_token.span;
34613460
self.dcx().emit_err(errors::ParenthesesInMatchPat {
34623461
span: vec![left, right],
@@ -4027,7 +4026,14 @@ pub(crate) enum ForbiddenLetReason {
40274026
NotSupportedParentheses(#[primary_span] Span),
40284027
}
40294028

4030-
/// Visitor to check for invalid/unstable use of `ExprKind::Let` that can't
4029+
/// Whether let chains are allowed on all editions, or it's edition dependent (allowed only on
4030+
/// 2024 and later). In case of edition dependence, specify the currently present edition.
4031+
pub enum LetChainsPolicy {
4032+
AlwaysAllowed,
4033+
EditionDependent { current_edition: Edition },
4034+
}
4035+
4036+
/// Visitor to check for invalid use of `ExprKind::Let` that can't
40314037
/// easily be caught in parsing. For example:
40324038
///
40334039
/// ```rust,ignore (example)
@@ -4038,19 +4044,29 @@ pub(crate) enum ForbiddenLetReason {
40384044
/// ```
40394045
struct CondChecker<'a> {
40404046
parser: &'a Parser<'a>,
4047+
let_chains_policy: LetChainsPolicy,
4048+
depth: u32,
40414049
forbid_let_reason: Option<ForbiddenLetReason>,
40424050
missing_let: Option<errors::MaybeMissingLet>,
40434051
comparison: Option<errors::MaybeComparison>,
40444052
}
40454053

40464054
impl<'a> CondChecker<'a> {
4047-
fn new(parser: &'a Parser<'a>) -> Self {
4048-
CondChecker { parser, forbid_let_reason: None, missing_let: None, comparison: None }
4055+
fn new(parser: &'a Parser<'a>, let_chains_policy: LetChainsPolicy) -> Self {
4056+
CondChecker {
4057+
parser,
4058+
forbid_let_reason: None,
4059+
missing_let: None,
4060+
comparison: None,
4061+
let_chains_policy,
4062+
depth: 0,
4063+
}
40494064
}
40504065
}
40514066

40524067
impl MutVisitor for CondChecker<'_> {
40534068
fn visit_expr(&mut self, e: &mut P<Expr>) {
4069+
self.depth += 1;
40544070
use ForbiddenLetReason::*;
40554071

40564072
let span = e.span;
@@ -4065,8 +4081,16 @@ impl MutVisitor for CondChecker<'_> {
40654081
comparison: self.comparison,
40664082
},
40674083
));
4068-
} else {
4069-
self.parser.psess.gated_spans.gate(sym::let_chains, span);
4084+
} else if self.depth > 1 {
4085+
// Top level `let` is always allowed; only gate chains
4086+
match self.let_chains_policy {
4087+
LetChainsPolicy::AlwaysAllowed => (),
4088+
LetChainsPolicy::EditionDependent { current_edition } => {
4089+
if !current_edition.at_least_rust_2024() || !span.at_least_rust_2024() {
4090+
self.parser.psess.gated_spans.gate(sym::let_chains, span);
4091+
}
4092+
}
4093+
}
40704094
}
40714095
}
40724096
ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, _, _) => {
@@ -4168,5 +4192,6 @@ impl MutVisitor for CondChecker<'_> {
41684192
// These would forbid any let expressions they contain already.
41694193
}
41704194
}
4195+
self.depth -= 1;
41714196
}
41724197
}

Diff for: tests/mir-opt/building/logical_or_in_conditional.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// skip-filecheck
22
//@ compile-flags: -Z validate-mir
3-
#![feature(let_chains)]
3+
//@ edition: 2024
44
struct Droppy(u8);
55
impl Drop for Droppy {
66
fn drop(&mut self) {

Diff for: tests/mir-opt/building/logical_or_in_conditional.test_complex.built.after.mir

+20-14
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ fn test_complex() -> () {
1919
bb0: {
2020
StorageLive(_1);
2121
StorageLive(_2);
22-
_2 = E::f() -> [return: bb1, unwind: bb34];
22+
_2 = E::f() -> [return: bb1, unwind: bb35];
2323
}
2424

2525
bb1: {
@@ -42,7 +42,7 @@ fn test_complex() -> () {
4242

4343
bb5: {
4444
StorageLive(_4);
45-
_4 = always_true() -> [return: bb6, unwind: bb34];
45+
_4 = always_true() -> [return: bb6, unwind: bb35];
4646
}
4747

4848
bb6: {
@@ -64,7 +64,7 @@ fn test_complex() -> () {
6464
}
6565

6666
bb9: {
67-
drop(_7) -> [return: bb11, unwind: bb34];
67+
drop(_7) -> [return: bb11, unwind: bb35];
6868
}
6969

7070
bb10: {
@@ -78,7 +78,7 @@ fn test_complex() -> () {
7878
}
7979

8080
bb12: {
81-
drop(_7) -> [return: bb13, unwind: bb34];
81+
drop(_7) -> [return: bb13, unwind: bb35];
8282
}
8383

8484
bb13: {
@@ -98,7 +98,7 @@ fn test_complex() -> () {
9898
}
9999

100100
bb15: {
101-
drop(_10) -> [return: bb17, unwind: bb34];
101+
drop(_10) -> [return: bb17, unwind: bb35];
102102
}
103103

104104
bb16: {
@@ -113,11 +113,12 @@ fn test_complex() -> () {
113113

114114
bb18: {
115115
_1 = const ();
116+
StorageDead(_2);
116117
goto -> bb22;
117118
}
118119

119120
bb19: {
120-
drop(_10) -> [return: bb20, unwind: bb34];
121+
drop(_10) -> [return: bb20, unwind: bb35];
121122
}
122123

123124
bb20: {
@@ -127,6 +128,7 @@ fn test_complex() -> () {
127128
}
128129

129130
bb21: {
131+
StorageDead(_2);
130132
_1 = const ();
131133
goto -> bb22;
132134
}
@@ -135,18 +137,17 @@ fn test_complex() -> () {
135137
StorageDead(_8);
136138
StorageDead(_5);
137139
StorageDead(_4);
138-
StorageDead(_2);
139140
StorageDead(_1);
140141
StorageLive(_11);
141-
_11 = always_true() -> [return: bb23, unwind: bb34];
142+
_11 = always_true() -> [return: bb23, unwind: bb35];
142143
}
143144

144145
bb23: {
145146
switchInt(move _11) -> [0: bb25, otherwise: bb24];
146147
}
147148

148149
bb24: {
149-
goto -> bb32;
150+
goto -> bb33;
150151
}
151152

152153
bb25: {
@@ -155,7 +156,7 @@ fn test_complex() -> () {
155156

156157
bb26: {
157158
StorageLive(_12);
158-
_12 = E::f() -> [return: bb27, unwind: bb34];
159+
_12 = E::f() -> [return: bb27, unwind: bb35];
159160
}
160161

161162
bb27: {
@@ -178,21 +179,26 @@ fn test_complex() -> () {
178179

179180
bb31: {
180181
_0 = const ();
181-
goto -> bb33;
182+
StorageDead(_12);
183+
goto -> bb34;
182184
}
183185

184186
bb32: {
185-
_0 = const ();
187+
StorageDead(_12);
186188
goto -> bb33;
187189
}
188190

189191
bb33: {
192+
_0 = const ();
193+
goto -> bb34;
194+
}
195+
196+
bb34: {
190197
StorageDead(_11);
191-
StorageDead(_12);
192198
return;
193199
}
194200

195-
bb34 (cleanup): {
201+
bb35 (cleanup): {
196202
resume;
197203
}
198204
}

Diff for: tests/ui/deriving/auxiliary/malicious-macro.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![feature(let_chains)]
1+
//@ edition: 2024
22

33
extern crate proc_macro;
44

Diff for: tests/ui/drop/drop-order-comparisons.e2021.fixed

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
//@ [e2024] edition: 2024
2525
//@ run-pass
2626

27-
#![feature(let_chains)]
27+
#![cfg_attr(e2021, feature(let_chains))]
2828
#![cfg_attr(e2021, warn(rust_2024_compatibility))]
2929

3030
fn t_bindings() {

Diff for: tests/ui/drop/drop-order-comparisons.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
//@ [e2024] edition: 2024
2525
//@ run-pass
2626

27-
#![feature(let_chains)]
27+
#![cfg_attr(e2021, feature(let_chains))]
2828
#![cfg_attr(e2021, warn(rust_2024_compatibility))]
2929

3030
fn t_bindings() {

Diff for: tests/ui/drop/drop_order.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
//@ compile-flags: -Z validate-mir
33
//@ revisions: edition2021 edition2024
44
//@ [edition2021] edition: 2021
5+
//@ [edition2024] compile-flags: -Z lint-mir
56
//@ [edition2024] edition: 2024
67

7-
#![feature(let_chains)]
8+
#![cfg_attr(edition2021, feature(let_chains))]
89

910
use std::cell::RefCell;
1011
use std::convert::TryInto;

Diff for: tests/ui/drop/drop_order_if_let_rescope.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
//@ run-pass
22
//@ edition:2024
3-
//@ compile-flags: -Z validate-mir
4-
5-
#![feature(let_chains)]
3+
//@ compile-flags: -Z validate-mir -Z lint-mir
64

75
use std::cell::RefCell;
86
use std::convert::TryInto;

Diff for: tests/ui/drop/issue-100276.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
//@ check-pass
22
//@ compile-flags: -Z validate-mir
3-
#![feature(let_chains)]
3+
//@ revisions: edition2021 edition2024
4+
//@ [edition2021] edition: 2021
5+
//@ [edition2024] compile-flags: -Z lint-mir
6+
//@ [edition2024] edition: 2024
7+
8+
#![cfg_attr(edition2021, feature(let_chains))]
49

510
fn let_chains(entry: std::io::Result<std::fs::DirEntry>) {
611
if let Ok(entry) = entry

Diff for: tests/ui/expr/if/attrs/let-chains-attr.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
//@ check-pass
2-
3-
#![feature(let_chains)]
2+
//@ edition:2024
43

54
#[cfg(false)]
65
fn foo() {

Diff for: tests/ui/lint/issue-121070-let-range.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//@ check-pass
2+
//@ edition:2024
23

3-
#![feature(let_chains)]
44
#![allow(irrefutable_let_patterns)]
55
fn main() {
66
let _a = 0..1;

Diff for: tests/ui/mir/issue-99852.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//@ check-pass
22
//@ compile-flags: -Z validate-mir
3-
#![feature(let_chains)]
3+
//@ edition: 2024
44

55
fn lambda<T, U>() -> U
66
where

0 commit comments

Comments
 (0)