1 use super::SAME_ITEM_PUSH;
2 use clippy_utils::diagnostics::span_lint_and_help;
3 use clippy_utils::path_to_local;
4 use clippy_utils::source::snippet_with_macro_callsite;
5 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
6 use if_chain::if_chain;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::intravisit::{walk_expr, Visitor};
10 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Node, Pat, PatKind, Stmt, StmtKind};
11 use rustc_lint::LateContext;
12 use rustc_span::symbol::sym;
13 use std::iter::Iterator;
15 /// Detects for loop pushing the same item into a Vec
16 pub(super) fn check<'tcx>(
17 cx: &LateContext<'tcx>,
23 fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) {
24 let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
25 let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
31 "it looks like the same item is being pushed into this Vec",
34 "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
35 item_str, vec_str, item_str
40 if !matches!(pat.kind, PatKind::Wild) {
44 // Determine whether it is safe to lint the body
45 let mut same_item_push_visitor = SameItemPushVisitor::new(cx);
46 walk_expr(&mut same_item_push_visitor, body);
48 if same_item_push_visitor.should_lint();
49 if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push;
50 let vec_ty = cx.typeck_results().expr_ty(vec);
51 let ty = vec_ty.walk().nth(1).unwrap().expect_ty();
56 .map_or(false, |id| implements_trait(cx, ty, id, &[]));
58 // Make sure that the push does not involve possibly mutating values
59 match pushed_item.kind {
60 ExprKind::Path(ref qpath) => {
61 match cx.qpath_res(qpath, pushed_item.hir_id) {
62 // immutable bindings that are initialized with literal or constant
63 Res::Local(hir_id) => {
64 let node = cx.tcx.hir().get(hir_id);
66 if let Node::Pat(pat) = node;
67 if let PatKind::Binding(bind_ann, ..) = pat.kind;
68 if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
69 let parent_node = cx.tcx.hir().get_parent_node(hir_id);
70 if let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node);
71 if let Some(init) = parent_let_expr.init;
74 // immutable bindings that are initialized with literal
75 ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
76 // immutable bindings that are initialized with constant
77 ExprKind::Path(ref path) => {
78 if let Res::Def(DefKind::Const, ..) = cx.qpath_res(path, init.hir_id) {
79 emit_lint(cx, vec, pushed_item);
88 Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
92 ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
99 // Scans the body of the for loop and determines whether lint should be given
100 struct SameItemPushVisitor<'a, 'tcx> {
101 non_deterministic_expr: bool,
102 multiple_pushes: bool,
103 // this field holds the last vec push operation visited, which should be the only push seen
104 vec_push: Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>,
105 cx: &'a LateContext<'tcx>,
106 used_locals: FxHashSet<HirId>,
109 impl<'a, 'tcx> SameItemPushVisitor<'a, 'tcx> {
110 fn new(cx: &'a LateContext<'tcx>) -> Self {
112 non_deterministic_expr: false,
113 multiple_pushes: false,
116 used_locals: FxHashSet::default(),
120 fn should_lint(&self) -> bool {
122 if !self.non_deterministic_expr;
123 if !self.multiple_pushes;
124 if let Some((vec, _)) = self.vec_push;
125 if let Some(hir_id) = path_to_local(vec);
127 !self.used_locals.contains(&hir_id)
135 impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
136 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
138 // Non-determinism may occur ... don't give a lint
139 ExprKind::Loop(..) | ExprKind::Match(..) | ExprKind::If(..) => self.non_deterministic_expr = true,
140 ExprKind::Block(block, _) => self.visit_block(block),
142 if let Some(hir_id) = path_to_local(expr) {
143 self.used_locals.insert(hir_id);
145 walk_expr(self, expr);
150 fn visit_block(&mut self, b: &'tcx Block<'_>) {
151 for stmt in b.stmts.iter() {
152 self.visit_stmt(stmt);
156 fn visit_stmt(&mut self, s: &'tcx Stmt<'_>) {
157 let vec_push_option = get_vec_push(self.cx, s);
158 if vec_push_option.is_none() {
159 // Current statement is not a push so visit inside
161 StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(expr),
165 // Current statement is a push ...check whether another
166 // push had been previously done
167 if self.vec_push.is_none() {
168 self.vec_push = vec_push_option;
170 // There are multiple pushes ... don't lint
171 self.multiple_pushes = true;
177 // Given some statement, determine if that statement is a push on a Vec. If it is, return
178 // the Vec being pushed into and the item being pushed
179 fn get_vec_push<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
181 // Extract method being called
182 if let StmtKind::Semi(semi_stmt) = &stmt.kind;
183 if let ExprKind::MethodCall(path, args, _) = &semi_stmt.kind;
184 // Figure out the parameters for the method call
185 if let Some(self_expr) = args.get(0);
186 if let Some(pushed_item) = args.get(1);
187 // Check that the method being called is push() on a Vec
188 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(self_expr), sym::Vec);
189 if path.ident.name.as_str() == "push";
191 return Some((self_expr, pushed_item))