Skip to content

Commit baab58a

Browse files
committed
Introduce multipart binding for let_unit_value
1 parent b9a19ca commit baab58a

File tree

1 file changed

+41
-14
lines changed

1 file changed

+41
-14
lines changed

clippy_lints/src/unit_types/let_unit_value.rs

+41-14
Original file line numberDiff line numberDiff line change
@@ -71,25 +71,52 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, local: &'tcx LetStmt<'_>) {
7171
local.span,
7272
"this let-binding has unit value",
7373
|diag| {
74+
let mut suggestions = Vec::new();
75+
76+
// Suggest omitting the `let` binding
7477
if let Some(expr) = &local.init {
7578
let mut app = Applicability::MachineApplicable;
7679
let snip = snippet_with_context(cx, expr.span, local.span.ctxt(), "()", &mut app).0;
77-
diag.span_suggestion(local.span, "omit the `let` binding", format!("{snip};"), app);
80+
suggestions.push((local.span, format!("{snip};")));
7881
}
7982

80-
if let PatKind::Binding(_, binding_hir_id, ident, ..) = local.pat.kind
81-
&& let Some(body_id) = cx.enclosing_body.as_ref()
82-
&& let body = cx.tcx.hir().body(*body_id)
83-
&& is_local_used(cx, body, binding_hir_id)
84-
{
85-
let identifier = ident.as_str();
86-
let mut visitor = UnitVariableCollector::new(binding_hir_id);
87-
walk_body(&mut visitor, body);
88-
visitor.spans.into_iter().for_each(|span| {
89-
let msg =
90-
format!("variable `{identifier}` of type `()` can be replaced with explicit `()`");
91-
diag.span_suggestion(span, msg, "()", Applicability::MachineApplicable);
92-
});
83+
// Check if this is a binding pattern
84+
if let PatKind::Binding(_, binding_hir_id, ident, ..) = local.pat.kind {
85+
if let Some(body_id) = cx.enclosing_body.as_ref() {
86+
let body = cx.tcx.hir().body(*body_id);
87+
88+
// Collect variable usages
89+
let mut visitor = UnitVariableCollector::new(binding_hir_id);
90+
walk_body(&mut visitor, body);
91+
92+
// Add suggestions for replacing variable usages
93+
let has_usages = !visitor.spans.is_empty();
94+
if has_usages {
95+
suggestions.extend(visitor.spans.into_iter().map(|span| (span, "()".to_string())));
96+
}
97+
98+
// Emit appropriate diagnostic based on whether there are usages
99+
if has_usages {
100+
diag.multipart_suggestion(
101+
"omit the `let` binding and replace variable usages with `()`",
102+
suggestions,
103+
Applicability::MachineApplicable,
104+
);
105+
} else {
106+
diag.multipart_suggestion(
107+
"omit the `let` binding",
108+
suggestions,
109+
Applicability::MachineApplicable,
110+
);
111+
}
112+
}
113+
} else {
114+
// Emit a simpler diagnostic if not a binding
115+
diag.multipart_suggestion(
116+
"omit the `let` binding",
117+
suggestions,
118+
Applicability::MachineApplicable,
119+
);
93120
}
94121
},
95122
);

0 commit comments

Comments
 (0)