Skip to content

Commit b903126

Browse files
committed
Changes to let_unit_value
* View through locals in `let_unit_value` when determining if inference is required * Don't remove typed let bindings for more functions
1 parent 4198013 commit b903126

File tree

6 files changed

+266
-73
lines changed

6 files changed

+266
-73
lines changed

clippy_lints/src/unit_types/let_unit_value.rs

Lines changed: 90 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,25 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::get_parent_node;
23
use clippy_utils::source::snippet_with_macro_callsite;
3-
use clippy_utils::visitors::for_each_value_source;
4+
use clippy_utils::visitors::{for_each_local_assignment, for_each_value_source};
45
use core::ops::ControlFlow;
56
use rustc_errors::Applicability;
67
use rustc_hir::def::{DefKind, Res};
7-
use rustc_hir::{Expr, ExprKind, PatKind, Stmt, StmtKind};
8+
use rustc_hir::{Expr, ExprKind, HirId, HirIdSet, Node, PatKind, QPath, Stmt, StmtKind, TyKind};
89
use rustc_lint::{LateContext, LintContext};
910
use rustc_middle::lint::in_external_macro;
10-
use rustc_middle::ty::{self, Ty, TypeFoldable, TypeSuperFoldable, TypeVisitor};
11+
use rustc_middle::ty;
1112

1213
use super::LET_UNIT_VALUE;
1314

14-
pub(super) fn check(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
15+
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
1516
if let StmtKind::Local(local) = stmt.kind
1617
&& let Some(init) = local.init
1718
&& !local.pat.span.from_expansion()
1819
&& !in_external_macro(cx.sess(), stmt.span)
1920
&& cx.typeck_results().pat_ty(local.pat).is_unit()
2021
{
21-
let needs_inferred = for_each_value_source(init, &mut |e| if needs_inferred_result_ty(cx, e) {
22-
ControlFlow::Continue(())
23-
} else {
24-
ControlFlow::Break(())
25-
}).is_continue();
26-
27-
if needs_inferred {
22+
if local.ty.is_some() && expr_needs_inferred_result(cx, init) {
2823
if !matches!(local.pat.kind, PatKind::Wild) {
2924
span_lint_and_then(
3025
cx,
@@ -63,48 +58,106 @@ pub(super) fn check(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
6358
}
6459
}
6560

66-
fn needs_inferred_result_ty(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
67-
let id = match e.kind {
61+
/// Checks sub-expressions which create the value returned by the given expression for whether
62+
/// return value inference is needed. This checks through locals to see if they also need inference
63+
/// at this point.
64+
///
65+
/// e.g.
66+
/// ```rust,ignore
67+
/// let bar = foo();
68+
/// let x: u32 = if true { baz() } else { bar };
69+
/// ```
70+
/// Here the sources of the value assigned to `x` would be `baz()`, and `foo()` via the
71+
/// initialization of `bar`. If both `foo` and `baz` have a return type which require type
72+
/// inference then this function would return `true`.
73+
fn expr_needs_inferred_result<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
74+
// The locals used for initialization which have yet to be checked.
75+
let mut locals_to_check = Vec::new();
76+
// All the locals which have been added to `locals_to_check`. Needed to prevent cycles.
77+
let mut seen_locals = HirIdSet::default();
78+
if !each_value_source_needs_inference(cx, e, &mut locals_to_check, &mut seen_locals) {
79+
return false;
80+
}
81+
while let Some(id) = locals_to_check.pop() {
82+
if let Some(Node::Local(l)) = get_parent_node(cx.tcx, id) {
83+
if !l.ty.map_or(true, |ty| matches!(ty.kind, TyKind::Infer)) {
84+
return false;
85+
}
86+
if let Some(e) = l.init {
87+
if !each_value_source_needs_inference(cx, e, &mut locals_to_check, &mut seen_locals) {
88+
return false;
89+
}
90+
} else if for_each_local_assignment(cx, id, |e| {
91+
if each_value_source_needs_inference(cx, e, &mut locals_to_check, &mut seen_locals) {
92+
ControlFlow::Continue(())
93+
} else {
94+
ControlFlow::Break(())
95+
}
96+
})
97+
.is_break()
98+
{
99+
return false;
100+
}
101+
}
102+
}
103+
104+
true
105+
}
106+
107+
fn each_value_source_needs_inference(
108+
cx: &LateContext<'_>,
109+
e: &Expr<'_>,
110+
locals_to_check: &mut Vec<HirId>,
111+
seen_locals: &mut HirIdSet,
112+
) -> bool {
113+
for_each_value_source(e, &mut |e| {
114+
if needs_inferred_result_ty(cx, e, locals_to_check, seen_locals) {
115+
ControlFlow::Continue(())
116+
} else {
117+
ControlFlow::Break(())
118+
}
119+
})
120+
.is_continue()
121+
}
122+
123+
fn needs_inferred_result_ty(
124+
cx: &LateContext<'_>,
125+
e: &Expr<'_>,
126+
locals_to_check: &mut Vec<HirId>,
127+
seen_locals: &mut HirIdSet,
128+
) -> bool {
129+
let (id, args) = match e.kind {
68130
ExprKind::Call(
69131
Expr {
70132
kind: ExprKind::Path(ref path),
71133
hir_id,
72134
..
73135
},
74-
_,
136+
args,
75137
) => match cx.qpath_res(path, *hir_id) {
76-
Res::Def(DefKind::AssocFn | DefKind::Fn, id) => id,
138+
Res::Def(DefKind::AssocFn | DefKind::Fn, id) => (id, args),
77139
_ => return false,
78140
},
79-
ExprKind::MethodCall(..) => match cx.typeck_results().type_dependent_def_id(e.hir_id) {
80-
Some(id) => id,
141+
ExprKind::MethodCall(_, args, _) => match cx.typeck_results().type_dependent_def_id(e.hir_id) {
142+
Some(id) => (id, args),
81143
None => return false,
82144
},
145+
ExprKind::Path(QPath::Resolved(None, path)) => {
146+
if let Res::Local(id) = path.res
147+
&& seen_locals.insert(id)
148+
{
149+
locals_to_check.push(id);
150+
}
151+
return true;
152+
},
83153
_ => return false,
84154
};
85155
let sig = cx.tcx.fn_sig(id).skip_binder();
86156
if let ty::Param(output_ty) = *sig.output().kind() {
87-
sig.inputs().iter().all(|&ty| !ty_contains_param(ty, output_ty.index))
157+
sig.inputs().iter().zip(args).all(|(&ty, arg)| {
158+
!ty.is_param(output_ty.index) || each_value_source_needs_inference(cx, arg, locals_to_check, seen_locals)
159+
})
88160
} else {
89161
false
90162
}
91163
}
92-
93-
fn ty_contains_param(ty: Ty<'_>, index: u32) -> bool {
94-
struct Visitor(u32);
95-
impl<'tcx> TypeVisitor<'tcx> for Visitor {
96-
type BreakTy = ();
97-
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
98-
if let ty::Param(ty) = *ty.kind() {
99-
if ty.index == self.0 {
100-
ControlFlow::BREAK
101-
} else {
102-
ControlFlow::CONTINUE
103-
}
104-
} else {
105-
ty.super_visit_with(self)
106-
}
107-
}
108-
}
109-
ty.visit_with(&mut Visitor(index)).is_break()
110-
}

clippy_lints/src/unit_types/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ declare_clippy_lint! {
9898

9999
declare_lint_pass!(UnitTypes => [LET_UNIT_VALUE, UNIT_CMP, UNIT_ARG]);
100100

101-
impl LateLintPass<'_> for UnitTypes {
102-
fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) {
101+
impl<'tcx> LateLintPass<'tcx> for UnitTypes {
102+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
103103
let_unit_value::check(cx, stmt);
104104
}
105105

clippy_utils/src/visitors.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,3 +617,49 @@ pub fn any_temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, e: &'tcx
617617
})
618618
.is_break()
619619
}
620+
621+
/// Runs the given function for each path expression referencing the given local which occur after
622+
/// the given expression.
623+
pub fn for_each_local_assignment<'tcx, B>(
624+
cx: &LateContext<'tcx>,
625+
local_id: HirId,
626+
f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
627+
) -> ControlFlow<B> {
628+
struct V<'cx, 'tcx, F, B> {
629+
cx: &'cx LateContext<'tcx>,
630+
local_id: HirId,
631+
res: ControlFlow<B>,
632+
f: F,
633+
}
634+
impl<'cx, 'tcx, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>, B> Visitor<'tcx> for V<'cx, 'tcx, F, B> {
635+
type NestedFilter = nested_filter::OnlyBodies;
636+
fn nested_visit_map(&mut self) -> Self::Map {
637+
self.cx.tcx.hir()
638+
}
639+
640+
fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) {
641+
if let ExprKind::Assign(lhs, rhs, _) = e.kind
642+
&& self.res.is_continue()
643+
&& path_to_local_id(lhs, self.local_id)
644+
{
645+
self.res = (self.f)(rhs);
646+
self.visit_expr(rhs);
647+
} else {
648+
walk_expr(self, e);
649+
}
650+
}
651+
}
652+
653+
if let Some(b) = get_enclosing_block(cx, local_id) {
654+
let mut v = V {
655+
cx,
656+
local_id,
657+
res: ControlFlow::Continue(()),
658+
f,
659+
};
660+
v.visit_block(b);
661+
v.res
662+
} else {
663+
ControlFlow::Continue(())
664+
}
665+
}

tests/ui/let_unit.fixed

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
// run-rustfix
22

33
#![warn(clippy::let_unit_value)]
4-
#![allow(clippy::no_effect)]
5-
#![allow(unused_variables)]
4+
#![allow(unused_variables, clippy::no_effect, clippy::needless_late_init, path_statements)]
65

76
macro_rules! let_and_return {
87
($n:expr) => {{
@@ -72,8 +71,8 @@ fn _returns_generic() {
7271
fn f3<T>(x: T) -> T {
7372
x
7473
}
75-
fn f4<T>(mut x: Vec<T>) -> T {
76-
x.pop().unwrap()
74+
fn f5<T: Default>(x: bool) -> Option<T> {
75+
x.then(|| T::default())
7776
}
7877

7978
let _: () = f(); // Ok
@@ -85,8 +84,12 @@ fn _returns_generic() {
8584
f3(()); // Lint
8685
f3(()); // Lint
8786

88-
f4(vec![()]); // Lint
89-
f4(vec![()]); // Lint
87+
// Should lint:
88+
// fn f4<T>(mut x: Vec<T>) -> T {
89+
// x.pop().unwrap()
90+
// }
91+
// let _: () = f4(vec![()]);
92+
// let x: () = f4(vec![()]);
9093

9194
// Ok
9295
let _: () = {
@@ -112,4 +115,51 @@ fn _returns_generic() {
112115
Some(1) => f2(3),
113116
Some(_) => (),
114117
};
118+
119+
let _: () = f5(true).unwrap();
120+
121+
#[allow(clippy::let_unit_value)]
122+
{
123+
let x = f();
124+
let y;
125+
let z;
126+
match 0 {
127+
0 => {
128+
y = f();
129+
z = f();
130+
},
131+
1 => {
132+
println!("test");
133+
y = f();
134+
z = f3(());
135+
},
136+
_ => panic!(),
137+
}
138+
139+
let x1;
140+
let x2;
141+
if true {
142+
x1 = f();
143+
x2 = x1;
144+
} else {
145+
x2 = f();
146+
x1 = x2;
147+
}
148+
149+
let opt;
150+
match f5(true) {
151+
Some(x) => opt = x,
152+
None => panic!(),
153+
};
154+
155+
#[warn(clippy::let_unit_value)]
156+
{
157+
let _: () = x;
158+
let _: () = y;
159+
z;
160+
let _: () = x1;
161+
let _: () = x2;
162+
let _: () = opt;
163+
}
164+
}
115165
}

0 commit comments

Comments
 (0)