1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::path_to_local;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::needs_ordered_drop;
5 use clippy_utils::visitors::{expr_visitor, expr_visitor_no_bodies, is_local_used};
6 use rustc_errors::{Applicability, MultiSpan};
7 use rustc_hir::intravisit::Visitor;
9 BindingAnnotation, Block, Expr, ExprKind, HirId, Local, LocalSource, MatchSource, Node, Pat, PatKind, Stmt,
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 declare_clippy_lint! {
18 /// Checks for late initializations that can be replaced by a `let` statement
19 /// with an initializer.
21 /// ### Why is this bad?
22 /// Assigning in the `let` statement is less repetitive.
59 #[clippy::version = "1.59.0"]
60 pub NEEDLESS_LATE_INIT,
62 "late initializations that can be replaced by a `let` statement with an initializer"
64 declare_lint_pass!(NeedlessLateInit => [NEEDLESS_LATE_INIT]);
66 fn contains_assign_expr<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'tcx>) -> bool {
68 expr_visitor(cx, |expr| {
69 if let ExprKind::Assign(..) = expr.kind {
80 fn contains_let(cond: &Expr<'_>) -> bool {
82 expr_visitor_no_bodies(|expr| {
83 if let ExprKind::Let(_) = expr.kind {
94 fn stmt_needs_ordered_drop(cx: &LateContext<'_>, stmt: &Stmt<'_>) -> bool {
95 let StmtKind::Local(local) = stmt.kind else { return false };
96 !local.pat.walk_short(|pat| {
97 if let PatKind::Binding(.., None) = pat.kind {
98 !needs_ordered_drop(cx, cx.typeck_results().pat_ty(pat))
114 fn from_expr(expr: &Expr<'_>, span: Span) -> Option<Self> {
115 if let ExprKind::Assign(lhs, rhs, _) = expr.kind {
116 if lhs.span.from_expansion() {
121 lhs_id: path_to_local(lhs)?,
123 rhs_span: rhs.span.source_callsite(),
131 fn new<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, binding_id: HirId) -> Option<LocalAssign> {
132 let assign = match expr.kind {
133 ExprKind::Block(Block { expr: Some(expr), .. }, _) => Self::from_expr(expr, expr.span),
134 ExprKind::Block(block, _) => {
136 if let Some((last, other_stmts)) = block.stmts.split_last();
137 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = last.kind;
139 let assign = Self::from_expr(expr, last.span)?;
141 // avoid visiting if not needed
142 if assign.lhs_id == binding_id;
143 if other_stmts.iter().all(|stmt| !contains_assign_expr(cx, stmt));
152 ExprKind::Assign(..) => Self::from_expr(expr, expr.span),
156 if assign.lhs_id == binding_id {
164 fn assignment_suggestions<'tcx>(
165 cx: &LateContext<'tcx>,
167 exprs: impl IntoIterator<Item = &'tcx Expr<'tcx>>,
168 ) -> Option<(Applicability, Vec<(Span, String)>)> {
169 let mut assignments = Vec::new();
172 let ty = cx.typeck_results().expr_ty(expr);
181 let assign = LocalAssign::new(cx, expr, binding_id)?;
183 assignments.push(assign);
186 let suggestions = assignments
188 .flat_map(|assignment| {
190 assignment.span.until(assignment.rhs_span),
191 assignment.rhs_span.shrink_to_hi().with_hi(assignment.span.hi()),
194 .map(|span| (span, String::new()))
195 .collect::<Vec<(Span, String)>>();
197 match suggestions.len() {
198 // All of `exprs` are never types
199 // https://github.com/rust-lang/rust-clippy/issues/8911
201 1 => Some((Applicability::MachineApplicable, suggestions)),
202 // multiple suggestions don't work with rustfix in multipart_suggest
203 // https://github.com/rust-lang/rustfix/issues/141
204 _ => Some((Applicability::Unspecified, suggestions)),
209 stmt: &'tcx Stmt<'tcx>,
210 expr: &'tcx Expr<'tcx>,
214 fn first_usage<'tcx>(
215 cx: &LateContext<'tcx>,
217 local_stmt_id: HirId,
218 block: &'tcx Block<'tcx>,
219 ) -> Option<Usage<'tcx>> {
220 let significant_drop = needs_ordered_drop(cx, cx.typeck_results().node_type(binding_id));
225 .skip_while(|stmt| stmt.hir_id != local_stmt_id)
227 .take_while(|stmt| !significant_drop || !stmt_needs_ordered_drop(cx, stmt))
228 .find(|&stmt| is_local_used(cx, stmt, binding_id))
229 .and_then(|stmt| match stmt.kind {
230 StmtKind::Expr(expr) => Some(Usage {
235 StmtKind::Semi(expr) => Some(Usage {
244 fn local_snippet_without_semicolon(cx: &LateContext<'_>, local: &Local<'_>) -> Option<String> {
245 let span = local.span.with_hi(match local.ty {
248 Some(ty) => ty.span.hi(),
251 None => local.pat.span.hi(),
254 snippet_opt(cx, span)
258 cx: &LateContext<'tcx>,
259 local: &'tcx Local<'tcx>,
260 local_stmt: &'tcx Stmt<'tcx>,
261 block: &'tcx Block<'tcx>,
264 let usage = first_usage(cx, binding_id, local_stmt.hir_id, block)?;
265 let binding_name = cx.tcx.hir().opt_name(binding_id)?;
266 let let_snippet = local_snippet_without_semicolon(cx, local)?;
268 match usage.expr.kind {
269 ExprKind::Assign(..) => {
270 let assign = LocalAssign::new(cx, usage.expr, binding_id)?;
271 let mut msg_span = MultiSpan::from_spans(vec![local_stmt.span, assign.span]);
272 msg_span.push_span_label(local_stmt.span, "created here");
273 msg_span.push_span_label(assign.span, "initialised here");
279 "unneeded late initialization",
281 diag.tool_only_span_suggestion(
285 Applicability::MachineApplicable,
288 diag.span_suggestion(
290 &format!("declare `{}` here", binding_name),
292 Applicability::MachineApplicable,
297 ExprKind::If(cond, then_expr, Some(else_expr)) if !contains_let(cond) => {
298 let (applicability, suggestions) = assignment_suggestions(cx, binding_id, [then_expr, else_expr])?;
304 "unneeded late initialization",
306 diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
308 diag.span_suggestion_verbose(
309 usage.stmt.span.shrink_to_lo(),
310 &format!("declare `{}` here", binding_name),
311 format!("{} = ", let_snippet),
315 diag.multipart_suggestion("remove the assignments from the branches", suggestions, applicability);
317 if usage.needs_semi {
318 diag.span_suggestion(
319 usage.stmt.span.shrink_to_hi(),
320 "add a semicolon after the `if` expression",
328 ExprKind::Match(_, arms, MatchSource::Normal) => {
329 let (applicability, suggestions) = assignment_suggestions(cx, binding_id, arms.iter().map(|arm| arm.body))?;
335 "unneeded late initialization",
337 diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
339 diag.span_suggestion_verbose(
340 usage.stmt.span.shrink_to_lo(),
341 &format!("declare `{}` here", binding_name),
342 format!("{} = ", let_snippet),
346 diag.multipart_suggestion(
347 "remove the assignments from the `match` arms",
352 if usage.needs_semi {
353 diag.span_suggestion(
354 usage.stmt.span.shrink_to_hi(),
355 "add a semicolon after the `match` expression",
369 impl<'tcx> LateLintPass<'tcx> for NeedlessLateInit {
370 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
371 let mut parents = cx.tcx.hir().parent_iter(local.hir_id);
376 kind: PatKind::Binding(BindingAnnotation::NONE, binding_id, _, None),
379 source: LocalSource::Normal,
382 if let Some((_, Node::Stmt(local_stmt))) = parents.next();
383 if let Some((_, Node::Block(block))) = parents.next();
386 check(cx, local, local_stmt, block, binding_id);