]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec_resize_to_zero.rs
Clippy fixes
[rust.git] / clippy_lints / src / vec_resize_to_zero.rs
1 use crate::utils::span_lint_and_then;
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Spanned;
8
9 use crate::utils::{match_def_path, paths};
10 use rustc_ast::ast::LitKind;
11 use rustc_hir as hir;
12
13 declare_clippy_lint! {
14     /// **What it does:** Finds occurences of `Vec::resize(0, an_int)`
15     ///
16     /// **Why is this bad?** This is probably an argument inversion mistake.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// vec!(1, 2, 3, 4, 5).resize(0, 5)
23     /// ```
24     pub VEC_RESIZE_TO_ZERO,
25     correctness,
26     "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
27 }
28
29 declare_lint_pass!(VecResizeToZero => [VEC_RESIZE_TO_ZERO]);
30
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VecResizeToZero {
32     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
33         if_chain! {
34             if let hir::ExprKind::MethodCall(path_segment, _, ref args, _) = expr.kind;
35             if let Some(method_def_id) = cx.tables.type_dependent_def_id(expr.hir_id);
36             if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3;
37             if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = args[1].kind;
38             if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = args[2].kind;
39             then {
40                 let method_call_span = expr.span.with_lo(path_segment.ident.span.lo());
41                 span_lint_and_then(
42                     cx,
43                     VEC_RESIZE_TO_ZERO,
44                     expr.span,
45                     "emptying a vector with `resize`",
46                     |db| {
47                         db.help("the arguments may be inverted...");
48                         db.span_suggestion(
49                             method_call_span,
50                             "...or you can empty the vector with",
51                             "clear()".to_string(),
52                             Applicability::MaybeIncorrect,
53                         );
54                     },
55                 );
56             }
57         }
58     }
59 }