Skip to content

Commit 88591ba

Browse files
committed
Auto merge of rust-lang#8666 - Jarcho:while_let_loop_7913, r=dswij
Don't lint `while_let_loop` when significant drop order would change fixes rust-lang#7226 fixes rust-lang#7913 fixes rust-lang#5717 For rust-lang#5717 it may not stay fully fixed. This is only completely fixed right now due to all the allowed drop impls have `#[may_dangle]` on their drop impls. This may get changed in the future based on how significant drops are determined, but the example listed with `RefCell` shouldn't break. changelog: Don't lint `while_let_loop` when the order of significant drops would change
2 parents 70f1d0d + adbc849 commit 88591ba

File tree

4 files changed

+207
-140
lines changed

4 files changed

+207
-140
lines changed

clippy_lints/src/loops/while_let_loop.rs

+50-56
Original file line numberDiff line numberDiff line change
@@ -2,71 +2,60 @@ use super::WHILE_LET_LOOP;
22
use clippy_utils::diagnostics::span_lint_and_sugg;
33
use clippy_utils::higher;
44
use clippy_utils::source::snippet_with_applicability;
5+
use clippy_utils::ty::needs_ordered_drop;
6+
use clippy_utils::visitors::any_temporaries_need_ordered_drop;
57
use rustc_errors::Applicability;
6-
use rustc_hir::{Block, Expr, ExprKind, MatchSource, Pat, StmtKind};
7-
use rustc_lint::{LateContext, LintContext};
8-
use rustc_middle::lint::in_external_macro;
8+
use rustc_hir::{Block, Expr, ExprKind, Local, MatchSource, Pat, StmtKind};
9+
use rustc_lint::LateContext;
910

1011
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &'tcx Block<'_>) {
11-
// extract the expression from the first statement (if any) in a block
12-
let inner_stmt_expr = extract_expr_from_first_stmt(loop_block);
13-
// or extract the first expression (if any) from the block
14-
if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(loop_block)) {
15-
if let Some(higher::IfLet {
16-
let_pat,
17-
let_expr,
18-
if_else: Some(if_else),
19-
..
20-
}) = higher::IfLet::hir(cx, inner)
21-
{
22-
if is_simple_break_expr(if_else) {
23-
could_be_while_let(cx, expr, let_pat, let_expr);
12+
let (init, has_trailing_exprs) = match (loop_block.stmts, loop_block.expr) {
13+
([stmt, stmts @ ..], expr) => {
14+
if let StmtKind::Local(&Local { init: Some(e), .. }) | StmtKind::Semi(e) | StmtKind::Expr(e) = stmt.kind {
15+
(e, !stmts.is_empty() || expr.is_some())
16+
} else {
17+
return;
2418
}
25-
}
26-
27-
if let ExprKind::Match(matchexpr, arms, MatchSource::Normal) = inner.kind {
28-
if arms.len() == 2
29-
&& arms[0].guard.is_none()
30-
&& arms[1].guard.is_none()
31-
&& is_simple_break_expr(arms[1].body)
32-
{
33-
could_be_while_let(cx, expr, arms[0].pat, matchexpr);
34-
}
35-
}
36-
}
37-
}
19+
},
20+
([], Some(e)) => (e, false),
21+
_ => return,
22+
};
3823

39-
/// If a block begins with a statement (possibly a `let` binding) and has an
40-
/// expression, return it.
41-
fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
42-
if let Some(first_stmt) = block.stmts.get(0) {
43-
if let StmtKind::Local(local) = first_stmt.kind {
44-
return local.init;
45-
}
24+
if let Some(if_let) = higher::IfLet::hir(cx, init)
25+
&& let Some(else_expr) = if_let.if_else
26+
&& is_simple_break_expr(else_expr)
27+
{
28+
could_be_while_let(cx, expr, if_let.let_pat, if_let.let_expr, has_trailing_exprs);
29+
} else if let ExprKind::Match(scrutinee, [arm1, arm2], MatchSource::Normal) = init.kind
30+
&& arm1.guard.is_none()
31+
&& arm2.guard.is_none()
32+
&& is_simple_break_expr(arm2.body)
33+
{
34+
could_be_while_let(cx, expr, arm1.pat, scrutinee, has_trailing_exprs);
4635
}
47-
None
4836
}
4937

50-
/// If a block begins with an expression (with or without semicolon), return it.
51-
fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
52-
match block.expr {
53-
Some(expr) if block.stmts.is_empty() => Some(expr),
54-
None if !block.stmts.is_empty() => match block.stmts[0].kind {
55-
StmtKind::Expr(expr) | StmtKind::Semi(expr) => Some(expr),
56-
StmtKind::Local(..) | StmtKind::Item(..) => None,
57-
},
58-
_ => None,
59-
}
38+
/// Returns `true` if expr contains a single break expression without a label or eub-expression.
39+
fn is_simple_break_expr(e: &Expr<'_>) -> bool {
40+
matches!(peel_blocks(e).kind, ExprKind::Break(dest, None) if dest.label.is_none())
6041
}
6142

62-
/// Returns `true` if expr contains a single break expr without destination label
63-
/// and
64-
/// passed expression. The expression may be within a block.
65-
fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
66-
match expr.kind {
67-
ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
68-
ExprKind::Block(b, _) => extract_first_expr(b).map_or(false, is_simple_break_expr),
69-
_ => false,
43+
/// Removes any blocks containing only a single expression.
44+
fn peel_blocks<'tcx>(e: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
45+
if let ExprKind::Block(b, _) = e.kind {
46+
match (b.stmts, b.expr) {
47+
([s], None) => {
48+
if let StmtKind::Expr(e) | StmtKind::Semi(e) = s.kind {
49+
peel_blocks(e)
50+
} else {
51+
e
52+
}
53+
},
54+
([], Some(e)) => peel_blocks(e),
55+
_ => e,
56+
}
57+
} else {
58+
e
7059
}
7160
}
7261

@@ -75,8 +64,13 @@ fn could_be_while_let<'tcx>(
7564
expr: &'tcx Expr<'_>,
7665
let_pat: &'tcx Pat<'_>,
7766
let_expr: &'tcx Expr<'_>,
67+
has_trailing_exprs: bool,
7868
) {
79-
if in_external_macro(cx.sess(), expr.span) {
69+
if has_trailing_exprs
70+
&& (needs_ordered_drop(cx, cx.typeck_results().expr_ty(let_expr))
71+
|| any_temporaries_need_ordered_drop(cx, let_expr))
72+
{
73+
// Switching to a `while let` loop will extend the lifetime of some values.
8074
return;
8175
}
8276

clippy_lints/src/matches/redundant_pattern_match.rs

+4-80
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,13 @@ use clippy_utils::diagnostics::span_lint_and_then;
33
use clippy_utils::source::snippet;
44
use clippy_utils::sugg::Sugg;
55
use clippy_utils::ty::needs_ordered_drop;
6-
use clippy_utils::{higher, match_def_path};
7-
use clippy_utils::{is_lang_ctor, is_trait_method, paths};
6+
use clippy_utils::visitors::any_temporaries_need_ordered_drop;
7+
use clippy_utils::{higher, is_lang_ctor, is_trait_method, match_def_path, paths};
88
use if_chain::if_chain;
99
use rustc_ast::ast::LitKind;
1010
use rustc_errors::Applicability;
1111
use rustc_hir::LangItem::{OptionNone, PollPending};
12-
use rustc_hir::{
13-
intravisit::{walk_expr, Visitor},
14-
Arm, Block, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp,
15-
};
12+
use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp};
1613
use rustc_lint::LateContext;
1714
use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty};
1815
use rustc_span::sym;
@@ -47,79 +44,6 @@ fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
4744
}
4845
}
4946

50-
// Checks if there are any temporaries created in the given expression for which drop order
51-
// matters.
52-
fn temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
53-
struct V<'a, 'tcx> {
54-
cx: &'a LateContext<'tcx>,
55-
res: bool,
56-
}
57-
impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
58-
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
59-
match expr.kind {
60-
// Taking the reference of a value leaves a temporary
61-
// e.g. In `&String::new()` the string is a temporary value.
62-
// Remaining fields are temporary values
63-
// e.g. In `(String::new(), 0).1` the string is a temporary value.
64-
ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
65-
if !matches!(expr.kind, ExprKind::Path(_)) {
66-
if needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
67-
self.res = true;
68-
} else {
69-
self.visit_expr(expr);
70-
}
71-
}
72-
},
73-
// the base type is always taken by reference.
74-
// e.g. In `(vec![0])[0]` the vector is a temporary value.
75-
ExprKind::Index(base, index) => {
76-
if !matches!(base.kind, ExprKind::Path(_)) {
77-
if needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
78-
self.res = true;
79-
} else {
80-
self.visit_expr(base);
81-
}
82-
}
83-
self.visit_expr(index);
84-
},
85-
// Method calls can take self by reference.
86-
// e.g. In `String::new().len()` the string is a temporary value.
87-
ExprKind::MethodCall(_, [self_arg, args @ ..], _) => {
88-
if !matches!(self_arg.kind, ExprKind::Path(_)) {
89-
let self_by_ref = self
90-
.cx
91-
.typeck_results()
92-
.type_dependent_def_id(expr.hir_id)
93-
.map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
94-
if self_by_ref && needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg)) {
95-
self.res = true;
96-
} else {
97-
self.visit_expr(self_arg);
98-
}
99-
}
100-
args.iter().for_each(|arg| self.visit_expr(arg));
101-
},
102-
// Either explicitly drops values, or changes control flow.
103-
ExprKind::DropTemps(_)
104-
| ExprKind::Ret(_)
105-
| ExprKind::Break(..)
106-
| ExprKind::Yield(..)
107-
| ExprKind::Block(Block { expr: None, .. }, _)
108-
| ExprKind::Loop(..) => (),
109-
110-
// Only consider the final expression.
111-
ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
112-
113-
_ => walk_expr(self, expr),
114-
}
115-
}
116-
}
117-
118-
let mut v = V { cx, res: false };
119-
v.visit_expr(expr);
120-
v.res
121-
}
122-
12347
fn find_sugg_for_if_let<'tcx>(
12448
cx: &LateContext<'tcx>,
12549
expr: &'tcx Expr<'_>,
@@ -191,7 +115,7 @@ fn find_sugg_for_if_let<'tcx>(
191115
// scrutinee would be, so they have to be considered as well.
192116
// e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
193117
// for the duration if body.
194-
let needs_drop = needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
118+
let needs_drop = needs_ordered_drop(cx, check_ty) || any_temporaries_need_ordered_drop(cx, let_expr);
195119

196120
// check that `while_let_on_iterator` lint does not trigger
197121
if_chain! {

clippy_utils/src/visitors.rs

+127-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1+
use crate::ty::needs_ordered_drop;
12
use crate::{get_enclosing_block, path_to_local_id};
23
use core::ops::ControlFlow;
34
use rustc_hir as hir;
4-
use rustc_hir::def::{DefKind, Res};
5+
use rustc_hir::def::{CtorKind, DefKind, Res};
56
use rustc_hir::intravisit::{self, walk_block, walk_expr, Visitor};
67
use rustc_hir::{
7-
Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Stmt, UnOp, UnsafeSource,
8-
Unsafety,
8+
Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Let, QPath, Stmt, UnOp,
9+
UnsafeSource, Unsafety,
910
};
1011
use rustc_lint::LateContext;
1112
use rustc_middle::hir::map::Map;
1213
use rustc_middle::hir::nested_filter;
13-
use rustc_middle::ty;
14+
use rustc_middle::ty::adjustment::Adjust;
15+
use rustc_middle::ty::{self, Ty, TypeckResults};
1416

1517
/// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
1618
/// bodies (i.e. closures) are visited.
@@ -494,3 +496,124 @@ pub fn for_each_local_use_after_expr<'tcx, B>(
494496
ControlFlow::Continue(())
495497
}
496498
}
499+
500+
// Calls the given function for every unconsumed temporary created by the expression. Note the
501+
// function is only guaranteed to be called for types which need to be dropped, but it may be called
502+
// for other types.
503+
pub fn for_each_unconsumed_temporary<'tcx, B>(
504+
cx: &LateContext<'tcx>,
505+
e: &'tcx Expr<'tcx>,
506+
mut f: impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
507+
) -> ControlFlow<B> {
508+
// Todo: Handle partially consumed values.
509+
fn helper<'tcx, B>(
510+
typeck: &'tcx TypeckResults<'tcx>,
511+
consume: bool,
512+
e: &'tcx Expr<'tcx>,
513+
f: &mut impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
514+
) -> ControlFlow<B> {
515+
if !consume
516+
|| matches!(
517+
typeck.expr_adjustments(e),
518+
[adjust, ..] if matches!(adjust.kind, Adjust::Borrow(_) | Adjust::Deref(_))
519+
)
520+
{
521+
match e.kind {
522+
ExprKind::Path(QPath::Resolved(None, p))
523+
if matches!(p.res, Res::Def(DefKind::Ctor(_, CtorKind::Const), _)) =>
524+
{
525+
f(typeck.expr_ty(e))?;
526+
},
527+
ExprKind::Path(_)
528+
| ExprKind::Unary(UnOp::Deref, _)
529+
| ExprKind::Index(..)
530+
| ExprKind::Field(..)
531+
| ExprKind::AddrOf(..) => (),
532+
_ => f(typeck.expr_ty(e))?,
533+
}
534+
}
535+
match e.kind {
536+
ExprKind::AddrOf(_, _, e)
537+
| ExprKind::Field(e, _)
538+
| ExprKind::Unary(UnOp::Deref, e)
539+
| ExprKind::Match(e, ..)
540+
| ExprKind::Let(&Let { init: e, .. }) => {
541+
helper(typeck, false, e, f)?;
542+
},
543+
ExprKind::Block(&Block { expr: Some(e), .. }, _)
544+
| ExprKind::Box(e)
545+
| ExprKind::Cast(e, _)
546+
| ExprKind::Unary(_, e) => {
547+
helper(typeck, true, e, f)?;
548+
},
549+
ExprKind::Call(callee, args) => {
550+
helper(typeck, true, callee, f)?;
551+
for arg in args {
552+
helper(typeck, true, arg, f)?;
553+
}
554+
},
555+
ExprKind::MethodCall(_, args, _) | ExprKind::Tup(args) | ExprKind::Array(args) => {
556+
for arg in args {
557+
helper(typeck, true, arg, f)?;
558+
}
559+
},
560+
ExprKind::Index(borrowed, consumed)
561+
| ExprKind::Assign(borrowed, consumed, _)
562+
| ExprKind::AssignOp(_, borrowed, consumed) => {
563+
helper(typeck, false, borrowed, f)?;
564+
helper(typeck, true, consumed, f)?;
565+
},
566+
ExprKind::Binary(_, lhs, rhs) => {
567+
helper(typeck, true, lhs, f)?;
568+
helper(typeck, true, rhs, f)?;
569+
},
570+
ExprKind::Struct(_, fields, default) => {
571+
for field in fields {
572+
helper(typeck, true, field.expr, f)?;
573+
}
574+
if let Some(default) = default {
575+
helper(typeck, false, default, f)?;
576+
}
577+
},
578+
ExprKind::If(cond, then, else_expr) => {
579+
helper(typeck, true, cond, f)?;
580+
helper(typeck, true, then, f)?;
581+
if let Some(else_expr) = else_expr {
582+
helper(typeck, true, else_expr, f)?;
583+
}
584+
},
585+
ExprKind::Type(e, _) => {
586+
helper(typeck, consume, e, f)?;
587+
},
588+
589+
// Either drops temporaries, jumps out of the current expression, or has no sub expression.
590+
ExprKind::DropTemps(_)
591+
| ExprKind::Ret(_)
592+
| ExprKind::Break(..)
593+
| ExprKind::Yield(..)
594+
| ExprKind::Block(..)
595+
| ExprKind::Loop(..)
596+
| ExprKind::Repeat(..)
597+
| ExprKind::Lit(_)
598+
| ExprKind::ConstBlock(_)
599+
| ExprKind::Closure { .. }
600+
| ExprKind::Path(_)
601+
| ExprKind::Continue(_)
602+
| ExprKind::InlineAsm(_)
603+
| ExprKind::Err => (),
604+
}
605+
ControlFlow::Continue(())
606+
}
607+
helper(cx.typeck_results(), true, e, &mut f)
608+
}
609+
610+
pub fn any_temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
611+
for_each_unconsumed_temporary(cx, e, |ty| {
612+
if needs_ordered_drop(cx, ty) {
613+
ControlFlow::Break(())
614+
} else {
615+
ControlFlow::Continue(())
616+
}
617+
})
618+
.is_break()
619+
}

0 commit comments

Comments
 (0)