]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_late_init.rs
a863a7990ca8cd2afb834d9ab6e413101c70cc00
[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::{expr_visitor, expr_visitor_no_bodies, is_local_used};
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::Visitor;
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.58.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     let mut seen = false;
68     expr_visitor(cx, |expr| {
69         if let ExprKind::Assign(..) = expr.kind {
70             seen = true;
71         }
72
73         !seen
74     })
75     .visit_stmt(stmt);
76
77     seen
78 }
79
80 fn contains_let(cond: &Expr<'_>) -> bool {
81     let mut seen = false;
82     expr_visitor_no_bodies(|expr| {
83         if let ExprKind::Let(_) = expr.kind {
84             seen = true;
85         }
86
87         !seen
88     })
89     .visit_expr(cond);
90
91     seen
92 }
93
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))
99         } else {
100             true
101         }
102     })
103 }
104
105 #[derive(Debug)]
106 struct LocalAssign {
107     lhs_id: HirId,
108     lhs_span: Span,
109     rhs_span: Span,
110     span: Span,
111 }
112
113 impl LocalAssign {
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() {
117                 return None;
118             }
119
120             Some(Self {
121                 lhs_id: path_to_local(lhs)?,
122                 lhs_span: lhs.span,
123                 rhs_span: rhs.span.source_callsite(),
124                 span,
125             })
126         } else {
127             None
128         }
129     }
130
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, _) => {
135                 if_chain! {
136                     if let Some((last, other_stmts)) = block.stmts.split_last();
137                     if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = last.kind;
138
139                     let assign = Self::from_expr(expr, last.span)?;
140
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));
144
145                     then {
146                         Some(assign)
147                     } else {
148                         None
149                     }
150                 }
151             },
152             ExprKind::Assign(..) => Self::from_expr(expr, expr.span),
153             _ => None,
154         }?;
155
156         if assign.lhs_id == binding_id {
157             Some(assign)
158         } else {
159             None
160         }
161     }
162 }
163
164 fn assignment_suggestions<'tcx>(
165     cx: &LateContext<'tcx>,
166     binding_id: HirId,
167     exprs: impl IntoIterator<Item = &'tcx Expr<'tcx>>,
168 ) -> Option<(Applicability, Vec<(Span, String)>)> {
169     let mut assignments = Vec::new();
170
171     for expr in exprs {
172         let ty = cx.typeck_results().expr_ty(expr);
173
174         if ty.is_never() {
175             continue;
176         }
177         if !ty.is_unit() {
178             return None;
179         }
180
181         let assign = LocalAssign::new(cx, expr, binding_id)?;
182
183         assignments.push(assign);
184     }
185
186     let suggestions = assignments
187         .iter()
188         .map(|assignment| Some((assignment.span.until(assignment.rhs_span), String::new())))
189         .chain(assignments.iter().map(|assignment| {
190             Some((
191                 assignment.rhs_span.shrink_to_hi().with_hi(assignment.span.hi()),
192                 String::new(),
193             ))
194         }))
195         .collect::<Option<Vec<(Span, String)>>>()?;
196
197     let applicability = if suggestions.len() > 1 {
198         // multiple suggestions don't work with rustfix in multipart_suggest
199         // https://github.com/rust-lang/rustfix/issues/141
200         Applicability::Unspecified
201     } else {
202         Applicability::MachineApplicable
203     };
204     Some((applicability, suggestions))
205 }
206
207 struct Usage<'tcx> {
208     stmt: &'tcx Stmt<'tcx>,
209     expr: &'tcx Expr<'tcx>,
210     needs_semi: bool,
211 }
212
213 fn first_usage<'tcx>(
214     cx: &LateContext<'tcx>,
215     binding_id: HirId,
216     local_stmt_id: HirId,
217     block: &'tcx Block<'tcx>,
218 ) -> Option<Usage<'tcx>> {
219     let significant_drop = needs_ordered_drop(cx, cx.typeck_results().node_type(binding_id));
220
221     block
222         .stmts
223         .iter()
224         .skip_while(|stmt| stmt.hir_id != local_stmt_id)
225         .skip(1)
226         .take_while(|stmt| !significant_drop || !stmt_needs_ordered_drop(cx, stmt))
227         .find(|&stmt| is_local_used(cx, stmt, binding_id))
228         .and_then(|stmt| match stmt.kind {
229             StmtKind::Expr(expr) => Some(Usage {
230                 stmt,
231                 expr,
232                 needs_semi: true,
233             }),
234             StmtKind::Semi(expr) => Some(Usage {
235                 stmt,
236                 expr,
237                 needs_semi: false,
238             }),
239             _ => None,
240         })
241 }
242
243 fn local_snippet_without_semicolon(cx: &LateContext<'_>, local: &Local<'_>) -> Option<String> {
244     let span = local.span.with_hi(match local.ty {
245         // let <pat>: <ty>;
246         // ~~~~~~~~~~~~~~~
247         Some(ty) => ty.span.hi(),
248         // let <pat>;
249         // ~~~~~~~~~
250         None => local.pat.span.hi(),
251     });
252
253     snippet_opt(cx, span)
254 }
255
256 fn check<'tcx>(
257     cx: &LateContext<'tcx>,
258     local: &'tcx Local<'tcx>,
259     local_stmt: &'tcx Stmt<'tcx>,
260     block: &'tcx Block<'tcx>,
261     binding_id: HirId,
262 ) -> Option<()> {
263     let usage = first_usage(cx, binding_id, local_stmt.hir_id, block)?;
264     let binding_name = cx.tcx.hir().opt_name(binding_id)?;
265     let let_snippet = local_snippet_without_semicolon(cx, local)?;
266
267     match usage.expr.kind {
268         ExprKind::Assign(..) => {
269             let assign = LocalAssign::new(cx, usage.expr, binding_id)?;
270
271             span_lint_and_then(
272                 cx,
273                 NEEDLESS_LATE_INIT,
274                 local_stmt.span,
275                 "unneeded late initialization",
276                 |diag| {
277                     diag.tool_only_span_suggestion(
278                         local_stmt.span,
279                         "remove the local",
280                         String::new(),
281                         Applicability::MachineApplicable,
282                     );
283
284                     diag.span_suggestion(
285                         assign.lhs_span,
286                         &format!("declare `{}` here", binding_name),
287                         let_snippet,
288                         Applicability::MachineApplicable,
289                     );
290                 },
291             );
292         },
293         ExprKind::If(cond, then_expr, Some(else_expr)) if !contains_let(cond) => {
294             let (applicability, suggestions) = assignment_suggestions(cx, binding_id, [then_expr, else_expr])?;
295
296             span_lint_and_then(
297                 cx,
298                 NEEDLESS_LATE_INIT,
299                 local_stmt.span,
300                 "unneeded late initialization",
301                 |diag| {
302                     diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
303
304                     diag.span_suggestion_verbose(
305                         usage.stmt.span.shrink_to_lo(),
306                         &format!("declare `{}` here", binding_name),
307                         format!("{} = ", let_snippet),
308                         applicability,
309                     );
310
311                     diag.multipart_suggestion("remove the assignments from the branches", suggestions, applicability);
312
313                     if usage.needs_semi {
314                         diag.span_suggestion(
315                             usage.stmt.span.shrink_to_hi(),
316                             "add a semicolon after the `if` expression",
317                             ";".to_string(),
318                             applicability,
319                         );
320                     }
321                 },
322             );
323         },
324         ExprKind::Match(_, arms, MatchSource::Normal) => {
325             let (applicability, suggestions) = assignment_suggestions(cx, binding_id, arms.iter().map(|arm| arm.body))?;
326
327             span_lint_and_then(
328                 cx,
329                 NEEDLESS_LATE_INIT,
330                 local_stmt.span,
331                 "unneeded late initialization",
332                 |diag| {
333                     diag.tool_only_span_suggestion(local_stmt.span, "remove the local", String::new(), applicability);
334
335                     diag.span_suggestion_verbose(
336                         usage.stmt.span.shrink_to_lo(),
337                         &format!("declare `{}` here", binding_name),
338                         format!("{} = ", let_snippet),
339                         applicability,
340                     );
341
342                     diag.multipart_suggestion(
343                         "remove the assignments from the `match` arms",
344                         suggestions,
345                         applicability,
346                     );
347
348                     if usage.needs_semi {
349                         diag.span_suggestion(
350                             usage.stmt.span.shrink_to_hi(),
351                             "add a semicolon after the `match` expression",
352                             ";".to_string(),
353                             applicability,
354                         );
355                     }
356                 },
357             );
358         },
359         _ => {},
360     };
361
362     Some(())
363 }
364
365 impl<'tcx> LateLintPass<'tcx> for NeedlessLateInit {
366     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
367         let mut parents = cx.tcx.hir().parent_iter(local.hir_id);
368
369         if_chain! {
370             if let Local {
371                 init: None,
372                 pat: &Pat {
373                     kind: PatKind::Binding(BindingAnnotation::Unannotated, binding_id, _, None),
374                     ..
375                 },
376                 source: LocalSource::Normal,
377                 ..
378             } = local;
379             if let Some((_, Node::Stmt(local_stmt))) = parents.next();
380             if let Some((_, Node::Block(block))) = parents.next();
381
382             then {
383                 check(cx, local, local_stmt, block, binding_id);
384             }
385         }
386     }
387 }