]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops/same_item_push.rs
Auto merge of #9379 - royrustdev:multi_assignments, r=llogiq
[rust.git] / clippy_lints / src / loops / same_item_push.rs
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;
14
15 /// Detects for loop pushing the same item into a Vec
16 pub(super) fn check<'tcx>(
17     cx: &LateContext<'tcx>,
18     pat: &'tcx Pat<'_>,
19     _: &'tcx Expr<'_>,
20     body: &'tcx Expr<'_>,
21     _: &'tcx Expr<'_>,
22 ) {
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, "");
26
27         span_lint_and_help(
28             cx,
29             SAME_ITEM_PUSH,
30             vec.span,
31             "it looks like the same item is being pushed into this Vec",
32             None,
33             &format!(
34                 "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
35                 item_str, vec_str, item_str
36             ),
37         );
38     }
39
40     if !matches!(pat.kind, PatKind::Wild) {
41         return;
42     }
43
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);
47     if_chain! {
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();
52         if cx
53             .tcx
54             .lang_items()
55             .clone_trait()
56             .map_or(false, |id| implements_trait(cx, ty, id, &[]));
57         then {
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);
65                             if_chain! {
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;
72                                 then {
73                                     match init.kind {
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);
80                                             }
81                                         }
82                                         _ => {},
83                                     }
84                                 }
85                             }
86                         },
87                         // constant
88                         Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
89                         _ => {},
90                     }
91                 },
92                 ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
93                 _ => {},
94             }
95         }
96     }
97 }
98
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>,
107 }
108
109 impl<'a, 'tcx> SameItemPushVisitor<'a, 'tcx> {
110     fn new(cx: &'a LateContext<'tcx>) -> Self {
111         Self {
112             non_deterministic_expr: false,
113             multiple_pushes: false,
114             vec_push: None,
115             cx,
116             used_locals: FxHashSet::default(),
117         }
118     }
119
120     fn should_lint(&self) -> bool {
121         if_chain! {
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);
126             then {
127                 !self.used_locals.contains(&hir_id)
128             } else {
129                 false
130             }
131         }
132     }
133 }
134
135 impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
136     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
137         match &expr.kind {
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),
141             _ => {
142                 if let Some(hir_id) = path_to_local(expr) {
143                     self.used_locals.insert(hir_id);
144                 }
145                 walk_expr(self, expr);
146             },
147         }
148     }
149
150     fn visit_block(&mut self, b: &'tcx Block<'_>) {
151         for stmt in b.stmts.iter() {
152             self.visit_stmt(stmt);
153         }
154     }
155
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
160             match &s.kind {
161                 StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(expr),
162                 _ => {},
163             }
164         } else {
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;
169             } else {
170                 // There are multiple pushes ... don't lint
171                 self.multiple_pushes = true;
172             }
173         }
174     }
175 }
176
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>)> {
180     if_chain! {
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";
190             then {
191                 return Some((self_expr, pushed_item))
192             }
193     }
194     None
195 }