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