]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_late_init.rs
Make the match checking configurable
[rust.git] / clippy_lints / src / needless_late_init.rs
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::{for_each_expr, for_each_expr_with_closures, is_local_used};
6 use core::ops::ControlFlow;
7 use rustc_errors::{Applicability, MultiSpan};
8 use rustc_hir::{
9     BindingAnnotation, Block, Expr, ExprKind, HirId, Local, LocalSource, MatchSource, Node, Pat, PatKind, Stmt,
10     StmtKind,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::Span;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for late initializations that can be replaced by a `let` statement
19     /// with an initializer.
20     ///
21     /// ### Why is this bad?
22     /// Assigning in the `let` statement is less repetitive.
23     ///
24     /// ### Example
25     /// ```rust
26     /// let a;
27     /// a = 1;
28     ///
29     /// let b;
30     /// match 3 {
31     ///     0 => b = "zero",
32     ///     1 => b = "one",
33     ///     _ => b = "many",
34     /// }
35     ///
36     /// let c;
37     /// if true {
38     ///     c = 1;
39     /// } else {
40     ///     c = -1;
41     /// }
42     /// ```
43     /// Use instead:
44     /// ```rust
45     /// let a = 1;
46     ///
47     /// let b = match 3 {
48     ///     0 => "zero",
49     ///     1 => "one",
50     ///     _ => "many",
51     /// };
52     ///
53     /// let c = if true {
54     ///     1
55     /// } else {
56     ///     -1
57     /// };
58     /// ```
59     #[clippy::version = "1.59.0"]
60     pub NEEDLESS_LATE_INIT,
61     style,
62     "late initializations that can be replaced by a `let` statement with an initializer"
63 }
64 declare_lint_pass!(NeedlessLateInit => [NEEDLESS_LATE_INIT]);
65
66 fn contains_assign_expr<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'tcx>) -> bool {
67     for_each_expr_with_closures(cx, stmt, |e| {
68         if matches!(e.kind, ExprKind::Assign(..)) {
69             ControlFlow::Break(())
70         } else {
71             ControlFlow::Continue(())
72         }
73     })
74     .is_some()
75 }
76
77 fn contains_let(cond: &Expr<'_>) -> bool {
78     for_each_expr(cond, |e| {
79         if matches!(e.kind, ExprKind::Let(_)) {
80             ControlFlow::Break(())
81         } else {
82             ControlFlow::Continue(())
83         }
84     })
85     .is_some()
86 }
87
88 fn stmt_needs_ordered_drop(cx: &LateContext<'_>, stmt: &Stmt<'_>) -> bool {
89     let StmtKind::Local(local) = stmt.kind else { return false };
90     !local.pat.walk_short(|pat| {
91         if let PatKind::Binding(.., None) = pat.kind {
92             !needs_ordered_drop(cx, cx.typeck_results().pat_ty(pat))
93         } else {
94             true
95         }
96     })
97 }
98
99 #[derive(Debug)]
100 struct LocalAssign {
101     lhs_id: HirId,
102     lhs_span: Span,
103     rhs_span: Span,
104     span: Span,
105 }
106
107 impl LocalAssign {
108     fn from_expr(expr: &Expr<'_>, span: Span) -> Option<Self> {
109         if let ExprKind::Assign(lhs, rhs, _) = expr.kind {
110             if lhs.span.from_expansion() {
111                 return None;
112             }
113
114             Some(Self {
115                 lhs_id: path_to_local(lhs)?,
116                 lhs_span: lhs.span,
117                 rhs_span: rhs.span.source_callsite(),
118                 span,
119             })
120         } else {
121             None
122         }
123     }
124
125     fn new<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, binding_id: HirId) -> Option<LocalAssign> {
126         let assign = match expr.kind {
127             ExprKind::Block(Block { expr: Some(expr), .. }, _) => Self::from_expr(expr, expr.span),
128             ExprKind::Block(block, _) => {
129                 if_chain! {
130                     if let Some((last, other_stmts)) = block.stmts.split_last();
131                     if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = last.kind;
132
133                     let assign = Self::from_expr(expr, last.span)?;
134
135                     // avoid visiting if not needed
136                     if assign.lhs_id == binding_id;
137                     if other_stmts.iter().all(|stmt| !contains_assign_expr(cx, stmt));
138
139                     then {
140                         Some(assign)
141                     } else {
142                         None
143                     }
144                 }
145             },
146             ExprKind::Assign(..) => Self::from_expr(expr, expr.span),
147             _ => None,
148         }?;
149
150         if assign.lhs_id == binding_id {
151             Some(assign)
152         } else {
153             None
154         }
155     }
156 }
157
158 fn assignment_suggestions<'tcx>(
159     cx: &LateContext<'tcx>,
160     binding_id: HirId,
161     exprs: impl IntoIterator<Item = &'tcx Expr<'tcx>>,
162 ) -> Option<(Applicability, Vec<(Span, String)>)> {
163     let mut assignments = Vec::new();
164
165     for expr in exprs {
166         let ty = cx.typeck_results().expr_ty(expr);
167
168         if ty.is_never() {
169             continue;
170         }
171         if !ty.is_unit() {
172             return None;
173         }
174
175         let assign = LocalAssign::new(cx, expr, binding_id)?;
176
177         assignments.push(assign);
178     }
179
180     let suggestions = assignments
181         .iter()
182         .flat_map(|assignment| {
183             [
184                 assignment.span.until(assignment.rhs_span),
185                 assignment.rhs_span.shrink_to_hi().with_hi(assignment.span.hi()),
186             ]
187         })
188         .map(|span| (span, String::new()))
189         .collect::<Vec<(Span, String)>>();
190
191     match suggestions.len() {
192         // All of `exprs` are never types
193         // https://github.com/rust-lang/rust-clippy/issues/8911
194         0 => None,
195         1 => Some((Applicability::MachineApplicable, suggestions)),
196         // multiple suggestions don't work with rustfix in multipart_suggest
197         // https://github.com/rust-lang/rustfix/issues/141
198         _ => Some((Applicability::Unspecified, suggestions)),
199     }
200 }
201
202 struct Usage<'tcx> {
203     stmt: &'tcx Stmt<'tcx>,
204     expr: &'tcx Expr<'tcx>,
205     needs_semi: bool,
206 }
207
208 fn first_usage<'tcx>(
209     cx: &LateContext<'tcx>,
210     binding_id: HirId,
211     local_stmt_id: HirId,
212     block: &'tcx Block<'tcx>,
213 ) -> Option<Usage<'tcx>> {
214     let significant_drop = needs_ordered_drop(cx, cx.typeck_results().node_type(binding_id));
215
216     block
217         .stmts
218         .iter()
219         .skip_while(|stmt| stmt.hir_id != local_stmt_id)
220         .skip(1)
221         .take_while(|stmt| !significant_drop || !stmt_needs_ordered_drop(cx, stmt))
222         .find(|&stmt| is_local_used(cx, stmt, binding_id))
223         .and_then(|stmt| match stmt.kind {
224             StmtKind::Expr(expr) => Some(Usage {
225                 stmt,
226                 expr,
227                 needs_semi: true,
228             }),
229             StmtKind::Semi(expr) => Some(Usage {
230                 stmt,
231                 expr,
232                 needs_semi: false,
233             }),
234             _ => None,
235         })
236 }
237
238 fn local_snippet_without_semicolon(cx: &LateContext<'_>, local: &Local<'_>) -> Option<String> {
239     let span = local.span.with_hi(match local.ty {
240         // let <pat>: <ty>;
241         // ~~~~~~~~~~~~~~~
242         Some(ty) => ty.span.hi(),
243         // let <pat>;
244         // ~~~~~~~~~
245         None => local.pat.span.hi(),
246     });
247
248     snippet_opt(cx, span)
249 }
250
251 fn check<'tcx>(
252     cx: &LateContext<'tcx>,
253     local: &'tcx Local<'tcx>,
254     local_stmt: &'tcx Stmt<'tcx>,
255     block: &'tcx Block<'tcx>,
256     binding_id: HirId,
257 ) -> Option<()> {
258     let usage = first_usage(cx, binding_id, local_stmt.hir_id, block)?;
259     let binding_name = cx.tcx.hir().opt_name(binding_id)?;
260     let let_snippet = local_snippet_without_semicolon(cx, local)?;
261
262     match usage.expr.kind {
263         ExprKind::Assign(..) => {
264             let assign = LocalAssign::new(cx, usage.expr, binding_id)?;
265             let mut msg_span = MultiSpan::from_spans(vec![local_stmt.span, assign.span]);
266             msg_span.push_span_label(local_stmt.span, "created here");
267             msg_span.push_span_label(assign.span, "initialised here");
268
269             span_lint_and_then(
270                 cx,
271                 NEEDLESS_LATE_INIT,
272                 msg_span,
273                 "unneeded late initialization",
274                 |diag| {
275                     diag.tool_only_span_suggestion(
276                         local_stmt.span,
277                         "remove the local",
278                         "",
279                         Applicability::MachineApplicable,
280                     );
281
282                     diag.span_suggestion(
283                         assign.lhs_span,
284                         &format!("declare `{binding_name}` here"),
285                         let_snippet,
286                         Applicability::MachineApplicable,
287                     );
288                 },
289             );
290         },
291         ExprKind::If(cond, then_expr, Some(else_expr)) if !contains_let(cond) => {
292             let (applicability, suggestions) = assignment_suggestions(cx, binding_id, [then_expr, else_expr])?;
293
294             span_lint_and_then(
295                 cx,
296                 NEEDLESS_LATE_INIT,
297                 local_stmt.span,
298                 "unneeded late initialization",
299                 |diag| {
300                     diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
301
302                     diag.span_suggestion_verbose(
303                         usage.stmt.span.shrink_to_lo(),
304                         &format!("declare `{binding_name}` here"),
305                         format!("{let_snippet} = "),
306                         applicability,
307                     );
308
309                     diag.multipart_suggestion("remove the assignments from the branches", suggestions, applicability);
310
311                     if usage.needs_semi {
312                         diag.span_suggestion(
313                             usage.stmt.span.shrink_to_hi(),
314                             "add a semicolon after the `if` expression",
315                             ";",
316                             applicability,
317                         );
318                     }
319                 },
320             );
321         },
322         ExprKind::Match(_, arms, MatchSource::Normal) => {
323             let (applicability, suggestions) = assignment_suggestions(cx, binding_id, arms.iter().map(|arm| arm.body))?;
324
325             span_lint_and_then(
326                 cx,
327                 NEEDLESS_LATE_INIT,
328                 local_stmt.span,
329                 "unneeded late initialization",
330                 |diag| {
331                     diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
332
333                     diag.span_suggestion_verbose(
334                         usage.stmt.span.shrink_to_lo(),
335                         &format!("declare `{binding_name}` here"),
336                         format!("{let_snippet} = "),
337                         applicability,
338                     );
339
340                     diag.multipart_suggestion(
341                         "remove the assignments from the `match` arms",
342                         suggestions,
343                         applicability,
344                     );
345
346                     if usage.needs_semi {
347                         diag.span_suggestion(
348                             usage.stmt.span.shrink_to_hi(),
349                             "add a semicolon after the `match` expression",
350                             ";",
351                             applicability,
352                         );
353                     }
354                 },
355             );
356         },
357         _ => {},
358     };
359
360     Some(())
361 }
362
363 impl<'tcx> LateLintPass<'tcx> for NeedlessLateInit {
364     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
365         let mut parents = cx.tcx.hir().parent_iter(local.hir_id);
366         if_chain! {
367             if let Local {
368                 init: None,
369                 pat: &Pat {
370                     kind: PatKind::Binding(BindingAnnotation::NONE, binding_id, _, None),
371                     ..
372                 },
373                 source: LocalSource::Normal,
374                 ..
375             } = local;
376             if let Some((_, Node::Stmt(local_stmt))) = parents.next();
377             if let Some((_, Node::Block(block))) = parents.next();
378
379             then {
380                 check(cx, local, local_stmt, block, binding_id);
381             }
382         }
383     }
384 }