rustc_lint/
if_let_rescope.rs

1use std::iter::repeat;
2use std::ops::ControlFlow;
3
4use hir::intravisit::Visitor;
5use rustc_ast::Recovered;
6use rustc_errors::{
7    Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic, SuggestionStyle,
8};
9use rustc_hir::{self as hir, HirIdSet};
10use rustc_macros::LintDiagnostic;
11use rustc_middle::ty::TyCtxt;
12use rustc_session::lint::{FutureIncompatibilityReason, LintId};
13use rustc_session::{declare_lint, impl_lint_pass};
14use rustc_span::Span;
15use rustc_span::edition::Edition;
16
17use crate::{LateContext, LateLintPass};
18
19declare_lint! {
20    /// The `if_let_rescope` lint detects cases where a temporary value with
21    /// significant drop is generated on the right hand side of `if let`
22    /// and suggests a rewrite into `match` when possible.
23    ///
24    /// ### Example
25    ///
26    /// ```rust,edition2021
27    /// #![warn(if_let_rescope)]
28    /// #![allow(unused_variables)]
29    ///
30    /// struct Droppy;
31    /// impl Drop for Droppy {
32    ///     fn drop(&mut self) {
33    ///         // Custom destructor, including this `drop` implementation, is considered
34    ///         // significant.
35    ///         // Rust does not check whether this destructor emits side-effects that can
36    ///         // lead to observable change in program semantics, when the drop order changes.
37    ///         // Rust biases to be on the safe side, so that you can apply discretion whether
38    ///         // this change indeed breaches any contract or specification that your code needs
39    ///         // to honour.
40    ///         println!("dropped");
41    ///     }
42    /// }
43    /// impl Droppy {
44    ///     fn get(&self) -> Option<u8> {
45    ///         None
46    ///     }
47    /// }
48    ///
49    /// fn main() {
50    ///     if let Some(value) = Droppy.get() {
51    ///         // do something
52    ///     } else {
53    ///         // do something else
54    ///     }
55    /// }
56    /// ```
57    ///
58    /// {{produces}}
59    ///
60    /// ### Explanation
61    ///
62    /// With Edition 2024, temporaries generated while evaluating `if let`s
63    /// will be dropped before the `else` block.
64    /// This lint captures a possible change in runtime behaviour due to
65    /// a change in sequence of calls to significant `Drop::drop` destructors.
66    ///
67    /// A significant [`Drop::drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html)
68    /// destructor here refers to an explicit, arbitrary implementation of the `Drop` trait on the type
69    /// with exceptions including `Vec`, `Box`, `Rc`, `BTreeMap` and `HashMap`
70    /// that are marked by the compiler otherwise so long that the generic types have
71    /// no significant destructor recursively.
72    /// In other words, a type has a significant drop destructor when it has a `Drop` implementation
73    /// or its destructor invokes a significant destructor on a type.
74    /// Since we cannot completely reason about the change by just inspecting the existence of
75    /// a significant destructor, this lint remains only a suggestion and is set to `allow` by default.
76    ///
77    /// Whenever possible, a rewrite into an equivalent `match` expression that
78    /// observe the same order of calls to such destructors is proposed by this lint.
79    /// Authors may take their own discretion whether the rewrite suggestion shall be
80    /// accepted, or rejected to continue the use of the `if let` expression.
81    pub IF_LET_RESCOPE,
82    Allow,
83    "`if let` assigns a shorter lifetime to temporary values being pattern-matched against in Edition 2024 and \
84    rewriting in `match` is an option to preserve the semantics up to Edition 2021",
85    @future_incompatible = FutureIncompatibleInfo {
86        reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2024),
87        reference: "<https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-if-let-scope.html>",
88    };
89}
90
91/// Lint for potential change in program semantics of `if let`s
92#[derive(Default)]
93pub(crate) struct IfLetRescope {
94    skip: HirIdSet,
95}
96
97fn expr_parent_is_else(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
98    let Some((_, hir::Node::Expr(expr))) = tcx.hir().parent_iter(hir_id).next() else {
99        return false;
100    };
101    let hir::ExprKind::If(_cond, _conseq, Some(alt)) = expr.kind else { return false };
102    alt.hir_id == hir_id
103}
104
105fn expr_parent_is_stmt(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
106    let mut parents = tcx.hir().parent_iter(hir_id);
107    let stmt = match parents.next() {
108        Some((_, hir::Node::Stmt(stmt))) => stmt,
109        Some((_, hir::Node::Block(_) | hir::Node::Arm(_))) => return true,
110        _ => return false,
111    };
112    let (hir::StmtKind::Semi(expr) | hir::StmtKind::Expr(expr)) = stmt.kind else { return false };
113    expr.hir_id == hir_id
114}
115
116fn match_head_needs_bracket(tcx: TyCtxt<'_>, expr: &hir::Expr<'_>) -> bool {
117    expr_parent_is_else(tcx, expr.hir_id) && matches!(expr.kind, hir::ExprKind::If(..))
118}
119
120impl IfLetRescope {
121    fn probe_if_cascade<'tcx>(&mut self, cx: &LateContext<'tcx>, mut expr: &'tcx hir::Expr<'tcx>) {
122        if self.skip.contains(&expr.hir_id) {
123            return;
124        }
125        let tcx = cx.tcx;
126        let source_map = tcx.sess.source_map();
127        let expr_end = match expr.kind {
128            hir::ExprKind::If(_cond, conseq, None) => conseq.span.shrink_to_hi(),
129            hir::ExprKind::If(_cond, _conseq, Some(alt)) => alt.span.shrink_to_hi(),
130            _ => return,
131        };
132        let mut add_bracket_to_match_head = match_head_needs_bracket(tcx, expr);
133        let mut significant_droppers = vec![];
134        let mut lifetime_ends = vec![];
135        let mut closing_brackets = 0;
136        let mut alt_heads = vec![];
137        let mut match_heads = vec![];
138        let mut consequent_heads = vec![];
139        let mut first_if_to_lint = None;
140        let mut first_if_to_rewrite = false;
141        let mut empty_alt = false;
142        while let hir::ExprKind::If(cond, conseq, alt) = expr.kind {
143            self.skip.insert(expr.hir_id);
144            // We are interested in `let` fragment of the condition.
145            // Otherwise, we probe into the `else` fragment.
146            if let hir::ExprKind::Let(&hir::LetExpr {
147                span,
148                pat,
149                init,
150                ty: ty_ascription,
151                recovered: Recovered::No,
152            }) = cond.kind
153            {
154                // Peel off round braces
155                let if_let_pat = source_map
156                    .span_take_while(expr.span, |&ch| ch == '(' || ch.is_whitespace())
157                    .between(init.span);
158                // The consequent fragment is always a block.
159                let before_conseq = conseq.span.shrink_to_lo();
160                let lifetime_end = source_map.end_point(conseq.span);
161
162                if let ControlFlow::Break(significant_dropper) =
163                    (FindSignificantDropper { cx }).visit_expr(init)
164                {
165                    first_if_to_lint = first_if_to_lint.or_else(|| Some((span, expr.hir_id)));
166                    significant_droppers.push(significant_dropper);
167                    lifetime_ends.push(lifetime_end);
168                    if ty_ascription.is_some()
169                        || !expr.span.can_be_used_for_suggestions()
170                        || !pat.span.can_be_used_for_suggestions()
171                        || !if_let_pat.can_be_used_for_suggestions()
172                        || !before_conseq.can_be_used_for_suggestions()
173                    {
174                        // Our `match` rewrites does not support type ascription,
175                        // so we just bail.
176                        // Alternatively when the span comes from proc macro expansion,
177                        // we will also bail.
178                        // FIXME(#101728): change this when type ascription syntax is stabilized again
179                    } else if let Ok(pat) = source_map.span_to_snippet(pat.span) {
180                        let emit_suggestion = |alt_span| {
181                            first_if_to_rewrite = true;
182                            if add_bracket_to_match_head {
183                                closing_brackets += 2;
184                                match_heads.push(SingleArmMatchBegin::WithOpenBracket(if_let_pat));
185                            } else {
186                                // Sometimes, wrapping `match` into a block is undesirable,
187                                // because the scrutinee temporary lifetime is shortened and
188                                // the proposed fix will not work.
189                                closing_brackets += 1;
190                                match_heads
191                                    .push(SingleArmMatchBegin::WithoutOpenBracket(if_let_pat));
192                            }
193                            consequent_heads.push(ConsequentRewrite { span: before_conseq, pat });
194                            if let Some(alt_span) = alt_span {
195                                alt_heads.push(AltHead(alt_span));
196                            }
197                        };
198                        if let Some(alt) = alt {
199                            let alt_head = conseq.span.between(alt.span);
200                            if alt_head.can_be_used_for_suggestions() {
201                                // We lint only when the `else` span is user code, too.
202                                emit_suggestion(Some(alt_head));
203                            }
204                        } else {
205                            // This is the end of the `if .. else ..` cascade.
206                            // We can stop here.
207                            emit_suggestion(None);
208                            empty_alt = true;
209                            break;
210                        }
211                    }
212                }
213            }
214            // At this point, any `if let` fragment in the cascade is definitely preceeded by `else`,
215            // so a opening bracket is mandatory before each `match`.
216            add_bracket_to_match_head = true;
217            if let Some(alt) = alt {
218                expr = alt;
219            } else {
220                break;
221            }
222        }
223        if let Some((span, hir_id)) = first_if_to_lint {
224            tcx.emit_node_span_lint(
225                IF_LET_RESCOPE,
226                hir_id,
227                span,
228                IfLetRescopeLint {
229                    significant_droppers,
230                    lifetime_ends,
231                    rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite {
232                        match_heads,
233                        consequent_heads,
234                        closing_brackets: ClosingBrackets {
235                            span: expr_end,
236                            count: closing_brackets,
237                            empty_alt,
238                        },
239                        alt_heads,
240                    }),
241                },
242            );
243        }
244    }
245}
246
247impl_lint_pass!(
248    IfLetRescope => [IF_LET_RESCOPE]
249);
250
251impl<'tcx> LateLintPass<'tcx> for IfLetRescope {
252    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
253        if expr.span.edition().at_least_rust_2024()
254            || cx.tcx.lints_that_dont_need_to_run(()).contains(&LintId::of(IF_LET_RESCOPE))
255        {
256            return;
257        }
258
259        if let hir::ExprKind::Loop(block, _label, hir::LoopSource::While, _span) = expr.kind
260            && let Some(value) = block.expr
261            && let hir::ExprKind::If(cond, _conseq, _alt) = value.kind
262            && let hir::ExprKind::Let(..) = cond.kind
263        {
264            // Recall that `while let` is lowered into this:
265            // ```
266            // loop {
267            //     if let .. { body } else { break; }
268            // }
269            // ```
270            // There is no observable change in drop order on the overall `if let` expression
271            // given that the `{ break; }` block is trivial so the edition change
272            // means nothing substantial to this `while` statement.
273            self.skip.insert(value.hir_id);
274            return;
275        }
276        if expr_parent_is_stmt(cx.tcx, expr.hir_id)
277            && matches!(expr.kind, hir::ExprKind::If(_cond, _conseq, None))
278        {
279            // `if let` statement without an `else` branch has no observable change
280            // so we can skip linting it
281            return;
282        }
283        self.probe_if_cascade(cx, expr);
284    }
285}
286
287#[derive(LintDiagnostic)]
288#[diag(lint_if_let_rescope)]
289struct IfLetRescopeLint {
290    #[label]
291    significant_droppers: Vec<Span>,
292    #[help]
293    lifetime_ends: Vec<Span>,
294    #[subdiagnostic]
295    rewrite: Option<IfLetRescopeRewrite>,
296}
297
298struct IfLetRescopeRewrite {
299    match_heads: Vec<SingleArmMatchBegin>,
300    consequent_heads: Vec<ConsequentRewrite>,
301    closing_brackets: ClosingBrackets,
302    alt_heads: Vec<AltHead>,
303}
304
305impl Subdiagnostic for IfLetRescopeRewrite {
306    fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>(
307        self,
308        diag: &mut Diag<'_, G>,
309        f: &F,
310    ) {
311        let mut suggestions = vec![];
312        for match_head in self.match_heads {
313            match match_head {
314                SingleArmMatchBegin::WithOpenBracket(span) => {
315                    suggestions.push((span, "{ match ".into()))
316                }
317                SingleArmMatchBegin::WithoutOpenBracket(span) => {
318                    suggestions.push((span, "match ".into()))
319                }
320            }
321        }
322        for ConsequentRewrite { span, pat } in self.consequent_heads {
323            suggestions.push((span, format!("{{ {pat} => ")));
324        }
325        for AltHead(span) in self.alt_heads {
326            suggestions.push((span, " _ => ".into()));
327        }
328        let closing_brackets = self.closing_brackets;
329        suggestions.push((
330            closing_brackets.span,
331            closing_brackets
332                .empty_alt
333                .then_some(" _ => {}".chars())
334                .into_iter()
335                .flatten()
336                .chain(repeat('}').take(closing_brackets.count))
337                .collect(),
338        ));
339        let msg = f(diag, crate::fluent_generated::lint_suggestion);
340        diag.multipart_suggestion_with_style(
341            msg,
342            suggestions,
343            Applicability::MachineApplicable,
344            SuggestionStyle::ShowCode,
345        );
346    }
347}
348
349struct AltHead(Span);
350
351struct ConsequentRewrite {
352    span: Span,
353    pat: String,
354}
355
356struct ClosingBrackets {
357    span: Span,
358    count: usize,
359    empty_alt: bool,
360}
361enum SingleArmMatchBegin {
362    WithOpenBracket(Span),
363    WithoutOpenBracket(Span),
364}
365
366struct FindSignificantDropper<'tcx, 'a> {
367    cx: &'a LateContext<'tcx>,
368}
369
370impl<'tcx, 'a> Visitor<'tcx> for FindSignificantDropper<'tcx, 'a> {
371    type Result = ControlFlow<Span>;
372
373    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
374        if self
375            .cx
376            .typeck_results()
377            .expr_ty(expr)
378            .has_significant_drop(self.cx.tcx, self.cx.typing_env())
379        {
380            return ControlFlow::Break(expr.span);
381        }
382        match expr.kind {
383            hir::ExprKind::ConstBlock(_)
384            | hir::ExprKind::Lit(_)
385            | hir::ExprKind::Path(_)
386            | hir::ExprKind::Assign(_, _, _)
387            | hir::ExprKind::AssignOp(_, _, _)
388            | hir::ExprKind::Break(_, _)
389            | hir::ExprKind::Continue(_)
390            | hir::ExprKind::Ret(_)
391            | hir::ExprKind::Become(_)
392            | hir::ExprKind::InlineAsm(_)
393            | hir::ExprKind::OffsetOf(_, _)
394            | hir::ExprKind::Repeat(_, _)
395            | hir::ExprKind::Err(_)
396            | hir::ExprKind::Struct(_, _, _)
397            | hir::ExprKind::Closure(_)
398            | hir::ExprKind::Block(_, _)
399            | hir::ExprKind::DropTemps(_)
400            | hir::ExprKind::Loop(_, _, _, _) => ControlFlow::Continue(()),
401
402            hir::ExprKind::Tup(exprs) | hir::ExprKind::Array(exprs) => {
403                for expr in exprs {
404                    self.visit_expr(expr)?;
405                }
406                ControlFlow::Continue(())
407            }
408            hir::ExprKind::Call(callee, args) => {
409                self.visit_expr(callee)?;
410                for expr in args {
411                    self.visit_expr(expr)?;
412                }
413                ControlFlow::Continue(())
414            }
415            hir::ExprKind::MethodCall(_, receiver, args, _) => {
416                self.visit_expr(receiver)?;
417                for expr in args {
418                    self.visit_expr(expr)?;
419                }
420                ControlFlow::Continue(())
421            }
422            hir::ExprKind::Index(left, right, _) | hir::ExprKind::Binary(_, left, right) => {
423                self.visit_expr(left)?;
424                self.visit_expr(right)
425            }
426            hir::ExprKind::Unary(_, expr)
427            | hir::ExprKind::Cast(expr, _)
428            | hir::ExprKind::Type(expr, _)
429            | hir::ExprKind::UnsafeBinderCast(_, expr, _)
430            | hir::ExprKind::Yield(expr, _)
431            | hir::ExprKind::AddrOf(_, _, expr)
432            | hir::ExprKind::Match(expr, _, _)
433            | hir::ExprKind::Field(expr, _)
434            | hir::ExprKind::Let(&hir::LetExpr {
435                init: expr,
436                span: _,
437                pat: _,
438                ty: _,
439                recovered: Recovered::No,
440            }) => self.visit_expr(expr),
441            hir::ExprKind::Let(_) => ControlFlow::Continue(()),
442
443            hir::ExprKind::If(cond, _, _) => {
444                if let hir::ExprKind::Let(hir::LetExpr {
445                    init,
446                    span: _,
447                    pat: _,
448                    ty: _,
449                    recovered: Recovered::No,
450                }) = cond.kind
451                {
452                    self.visit_expr(init)?;
453                }
454                ControlFlow::Continue(())
455            }
456        }
457    }
458}