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