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::visitors::{expr_visitor, is_local_used};
5 use rustc_errors::Applicability;
6 use rustc_hir::intravisit::Visitor;
7 use rustc_hir::{Block, Expr, ExprKind, HirId, Local, LocalSource, MatchSource, Node, Pat, PatKind, Stmt, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
14 /// Checks for late initializations that can be replaced by a `let` statement
15 /// with an initializer.
17 /// ### Why is this bad?
18 /// Assigning in the `let` statement is less repetitive.
55 #[clippy::version = "1.58.0"]
56 pub NEEDLESS_LATE_INIT,
58 "late initializations that can be replaced by a `let` statement with an initializer"
60 declare_lint_pass!(NeedlessLateInit => [NEEDLESS_LATE_INIT]);
62 fn contains_assign_expr<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'tcx>) -> bool {
64 expr_visitor(cx, |expr| {
65 if let ExprKind::Assign(..) = expr.kind {
85 fn from_expr(expr: &Expr<'_>, span: Span) -> Option<Self> {
86 if let ExprKind::Assign(lhs, rhs, _) = expr.kind {
87 if lhs.span.from_expansion() {
92 lhs_id: path_to_local(lhs)?,
94 rhs_span: rhs.span.source_callsite(),
102 fn new<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, binding_id: HirId) -> Option<LocalAssign> {
103 let assign = match expr.kind {
104 ExprKind::Block(Block { expr: Some(expr), .. }, _) => Self::from_expr(expr, expr.span),
105 ExprKind::Block(block, _) => {
107 if let Some((last, other_stmts)) = block.stmts.split_last();
108 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = last.kind;
110 let assign = Self::from_expr(expr, last.span)?;
112 // avoid visiting if not needed
113 if assign.lhs_id == binding_id;
114 if other_stmts.iter().all(|stmt| !contains_assign_expr(cx, stmt));
123 ExprKind::Assign(..) => Self::from_expr(expr, expr.span),
127 if assign.lhs_id == binding_id {
135 fn assignment_suggestions<'tcx>(
136 cx: &LateContext<'tcx>,
138 exprs: impl IntoIterator<Item = &'tcx Expr<'tcx>>,
139 ) -> Option<(Applicability, Vec<(Span, String)>)> {
140 let mut assignments = Vec::new();
143 let ty = cx.typeck_results().expr_ty(expr);
152 let assign = LocalAssign::new(cx, expr, binding_id)?;
154 assignments.push(assign);
157 let suggestions = assignments
159 .map(|assignment| Some((assignment.span, snippet_opt(cx, assignment.rhs_span)?)))
160 .collect::<Option<Vec<(Span, String)>>>()?;
162 let applicability = if suggestions.len() > 1 {
163 // multiple suggestions don't work with rustfix in multipart_suggest
164 // https://github.com/rust-lang/rustfix/issues/141
165 Applicability::Unspecified
167 Applicability::MachineApplicable
169 Some((applicability, suggestions))
173 stmt: &'tcx Stmt<'tcx>,
174 expr: &'tcx Expr<'tcx>,
178 fn first_usage<'tcx>(
179 cx: &LateContext<'tcx>,
181 local_stmt_id: HirId,
182 block: &'tcx Block<'tcx>,
183 ) -> Option<Usage<'tcx>> {
187 .skip_while(|stmt| stmt.hir_id != local_stmt_id)
189 .find(|&stmt| is_local_used(cx, stmt, binding_id))
190 .and_then(|stmt| match stmt.kind {
191 StmtKind::Expr(expr) => Some(Usage {
196 StmtKind::Semi(expr) => Some(Usage {
205 fn local_snippet_without_semicolon(cx: &LateContext<'_>, local: &Local<'_>) -> Option<String> {
206 let span = local.span.with_hi(match local.ty {
209 Some(ty) => ty.span.hi(),
212 None => local.pat.span.hi(),
215 snippet_opt(cx, span)
219 cx: &LateContext<'tcx>,
220 local: &'tcx Local<'tcx>,
221 local_stmt: &'tcx Stmt<'tcx>,
222 block: &'tcx Block<'tcx>,
225 let usage = first_usage(cx, binding_id, local_stmt.hir_id, block)?;
226 let binding_name = cx.tcx.hir().opt_name(binding_id)?;
227 let let_snippet = local_snippet_without_semicolon(cx, local)?;
229 match usage.expr.kind {
230 ExprKind::Assign(..) => {
231 let assign = LocalAssign::new(cx, usage.expr, binding_id)?;
237 "unneeded late initalization",
239 diag.tool_only_span_suggestion(
243 Applicability::MachineApplicable,
246 diag.span_suggestion(
248 &format!("declare `{}` here", binding_name),
250 Applicability::MachineApplicable,
255 ExprKind::If(_, then_expr, Some(else_expr)) => {
256 let (applicability, suggestions) = assignment_suggestions(cx, binding_id, [then_expr, else_expr])?;
262 "unneeded late initalization",
264 diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
266 diag.span_suggestion_verbose(
267 usage.stmt.span.shrink_to_lo(),
268 &format!("declare `{}` here", binding_name),
269 format!("{} = ", let_snippet),
273 diag.multipart_suggestion("remove the assignments from the branches", suggestions, applicability);
275 if usage.needs_semi {
276 diag.span_suggestion(
277 usage.stmt.span.shrink_to_hi(),
278 "add a semicolon after the `if` expression",
286 ExprKind::Match(_, arms, MatchSource::Normal) => {
287 let (applicability, suggestions) = assignment_suggestions(cx, binding_id, arms.iter().map(|arm| arm.body))?;
293 "unneeded late initalization",
295 diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
297 diag.span_suggestion_verbose(
298 usage.stmt.span.shrink_to_lo(),
299 &format!("declare `{}` here", binding_name),
300 format!("{} = ", let_snippet),
304 diag.multipart_suggestion(
305 "remove the assignments from the `match` arms",
310 if usage.needs_semi {
311 diag.span_suggestion(
312 usage.stmt.span.shrink_to_hi(),
313 "add a semicolon after the `match` expression",
327 impl LateLintPass<'tcx> for NeedlessLateInit {
328 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
329 let mut parents = cx.tcx.hir().parent_iter(local.hir_id);
335 kind: PatKind::Binding(_, binding_id, _, None),
338 source: LocalSource::Normal,
341 if let Some((_, Node::Stmt(local_stmt))) = parents.next();
342 if let Some((_, Node::Block(block))) = parents.next();
345 check(cx, local, local_stmt, block, binding_id);