]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Rollup merge of #97415 - cjgillot:is-late-bound-solo, r=estebank
[rust.git] / clippy_lints / src / shadow.rs
1 use clippy_utils::diagnostics::span_lint_and_note;
2 use clippy_utils::source::snippet;
3 use clippy_utils::visitors::is_local_used;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_hir::def::Res;
6 use rustc_hir::def_id::LocalDefId;
7 use rustc_hir::hir_id::ItemLocalId;
8 use rustc_hir::{
9     Block, Body, BodyOwnerKind, Expr, ExprKind, HirId, Let, Node, Pat, PatKind, QPath, UnOp,
10 };
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::{Span, Symbol};
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for bindings that shadow other bindings already in
18     /// scope, while just changing reference level or mutability.
19     ///
20     /// ### Why is this bad?
21     /// Not much, in fact it's a very common pattern in Rust
22     /// code. Still, some may opt to avoid it in their code base, they can set this
23     /// lint to `Warn`.
24     ///
25     /// ### Example
26     /// ```rust
27     /// # let x = 1;
28     /// // Bad
29     /// let x = &x;
30     ///
31     /// // Good
32     /// let y = &x; // use different variable name
33     /// ```
34     #[clippy::version = "pre 1.29.0"]
35     pub SHADOW_SAME,
36     restriction,
37     "rebinding a name to itself, e.g., `let mut x = &mut x`"
38 }
39
40 declare_clippy_lint! {
41     /// ### What it does
42     /// Checks for bindings that shadow other bindings already in
43     /// scope, while reusing the original value.
44     ///
45     /// ### Why is this bad?
46     /// Not too much, in fact it's a common pattern in Rust
47     /// code. Still, some argue that name shadowing like this hurts readability,
48     /// because a value may be bound to different things depending on position in
49     /// the code.
50     ///
51     /// ### Example
52     /// ```rust
53     /// let x = 2;
54     /// let x = x + 1;
55     /// ```
56     /// use different variable name:
57     /// ```rust
58     /// let x = 2;
59     /// let y = x + 1;
60     /// ```
61     #[clippy::version = "pre 1.29.0"]
62     pub SHADOW_REUSE,
63     restriction,
64     "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
65 }
66
67 declare_clippy_lint! {
68     /// ### What it does
69     /// Checks for bindings that shadow other bindings already in
70     /// scope, either without an initialization or with one that does not even use
71     /// the original value.
72     ///
73     /// ### Why is this bad?
74     /// Name shadowing can hurt readability, especially in
75     /// large code bases, because it is easy to lose track of the active binding at
76     /// any place in the code. This can be alleviated by either giving more specific
77     /// names to bindings or introducing more scopes to contain the bindings.
78     ///
79     /// ### Example
80     /// ```rust
81     /// # let y = 1;
82     /// # let z = 2;
83     /// let x = y;
84     ///
85     /// // Bad
86     /// let x = z; // shadows the earlier binding
87     ///
88     /// // Good
89     /// let w = z; // use different variable name
90     /// ```
91     #[clippy::version = "pre 1.29.0"]
92     pub SHADOW_UNRELATED,
93     restriction,
94     "rebinding a name without even using the original value"
95 }
96
97 #[derive(Default)]
98 pub(crate) struct Shadow {
99     bindings: Vec<FxHashMap<Symbol, Vec<ItemLocalId>>>,
100 }
101
102 impl_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
103
104 impl<'tcx> LateLintPass<'tcx> for Shadow {
105     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
106         let (id, ident) = match pat.kind {
107             PatKind::Binding(_, hir_id, ident, _) => (hir_id, ident),
108             _ => return,
109         };
110
111         if pat.span.desugaring_kind().is_some() {
112             return;
113         }
114
115         if ident.span.from_expansion() || ident.span.is_dummy() {
116             return;
117         }
118
119         let HirId { owner, local_id } = id;
120         // get (or insert) the list of items for this owner and symbol
121         let data = self.bindings.last_mut().unwrap();
122         let items_with_name = data.entry(ident.name).or_default();
123
124         // check other bindings with the same name, most recently seen first
125         for &prev in items_with_name.iter().rev() {
126             if prev == local_id {
127                 // repeated binding in an `Or` pattern
128                 return;
129             }
130
131             if is_shadow(cx, owner, prev, local_id) {
132                 let prev_hir_id = HirId { owner, local_id: prev };
133                 lint_shadow(cx, pat, prev_hir_id, ident.span);
134                 // only lint against the "nearest" shadowed binding
135                 break;
136             }
137         }
138         // store the binding
139         items_with_name.push(local_id);
140     }
141
142     fn check_body(&mut self, cx: &LateContext<'_>, body: &Body<'_>) {
143         let hir = cx.tcx.hir();
144         if !matches!(hir.body_owner_kind(hir.body_owner_def_id(body.id())), BodyOwnerKind::Closure)
145         {
146             self.bindings.push(FxHashMap::default());
147         }
148     }
149
150     fn check_body_post(&mut self, cx: &LateContext<'_>, body: &Body<'_>) {
151         let hir = cx.tcx.hir();
152         if !matches!(hir.body_owner_kind(hir.body_owner_def_id(body.id())), BodyOwnerKind::Closure)
153         {
154             self.bindings.pop();
155         }
156     }
157 }
158
159 fn is_shadow(
160     cx: &LateContext<'_>,
161     owner: LocalDefId,
162     first: ItemLocalId,
163     second: ItemLocalId,
164 ) -> bool {
165     let scope_tree = cx.tcx.region_scope_tree(owner);
166     let first_scope = scope_tree.var_scope(first).unwrap();
167     let second_scope = scope_tree.var_scope(second).unwrap();
168     scope_tree.is_subscope_of(second_scope, first_scope)
169 }
170
171 fn lint_shadow(cx: &LateContext<'_>, pat: &Pat<'_>, shadowed: HirId, span: Span) {
172     let (lint, msg) = match find_init(cx, pat.hir_id) {
173         Some(expr) if is_self_shadow(cx, pat, expr, shadowed) => {
174             let msg = format!(
175                 "`{}` is shadowed by itself in `{}`",
176                 snippet(cx, pat.span, "_"),
177                 snippet(cx, expr.span, "..")
178             );
179             (SHADOW_SAME, msg)
180         }
181         Some(expr) if is_local_used(cx, expr, shadowed) => {
182             let msg = format!("`{}` is shadowed", snippet(cx, pat.span, "_"));
183             (SHADOW_REUSE, msg)
184         }
185         _ => {
186             let msg =
187                 format!("`{}` shadows a previous, unrelated binding", snippet(cx, pat.span, "_"));
188             (SHADOW_UNRELATED, msg)
189         }
190     };
191     span_lint_and_note(
192         cx,
193         lint,
194         span,
195         &msg,
196         Some(cx.tcx.hir().span(shadowed)),
197         "previous binding is here",
198     );
199 }
200
201 /// Returns true if the expression is a simple transformation of a local binding such as `&x`
202 fn is_self_shadow(cx: &LateContext<'_>, pat: &Pat<'_>, mut expr: &Expr<'_>, hir_id: HirId) -> bool {
203     let hir = cx.tcx.hir();
204     let is_direct_binding = hir
205         .parent_iter(pat.hir_id)
206         .map_while(|(_id, node)| match node {
207             Node::Pat(pat) => Some(pat),
208             _ => None,
209         })
210         .all(|pat| matches!(pat.kind, PatKind::Ref(..) | PatKind::Or(_)));
211     if !is_direct_binding {
212         return false;
213     }
214     loop {
215         expr = match expr.kind {
216             ExprKind::Box(e)
217             | ExprKind::AddrOf(_, _, e)
218             | ExprKind::Block(&Block { stmts: [], expr: Some(e), .. }, _)
219             | ExprKind::Unary(UnOp::Deref, e) => e,
220             ExprKind::Path(QPath::Resolved(None, path)) => break path.res == Res::Local(hir_id),
221             _ => break false,
222         }
223     }
224 }
225
226 /// Finds the "init" expression for a pattern: `let <pat> = <init>;` (or `if let`) or
227 /// `match <init> { .., <pat> => .., .. }`
228 fn find_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
229     for (_, node) in cx.tcx.hir().parent_iter(hir_id) {
230         let init = match node {
231             Node::Arm(_) | Node::Pat(_) => continue,
232             Node::Expr(expr) => match expr.kind {
233                 ExprKind::Match(e, _, _) | ExprKind::Let(&Let { init: e, .. }) => Some(e),
234                 _ => None,
235             },
236             Node::Local(local) => local.init,
237             _ => None,
238         };
239         return init;
240     }
241     None
242 }