]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Run rustfmt on clippy_lints
[rust.git] / clippy_lints / src / shadow.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::reexport::*;
11 use crate::rustc::hir::intravisit::FnKind;
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
14 use crate::rustc::ty;
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::syntax::source_map::Span;
17 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
18
19 /// **What it does:** Checks for bindings that shadow other bindings already in
20 /// scope, while just changing reference level or mutability.
21 ///
22 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
23 /// code. Still, some may opt to avoid it in their code base, they can set this
24 /// lint to `Warn`.
25 ///
26 /// **Known problems:** This lint, as the other shadowing related lints,
27 /// currently only catches very simple patterns.
28 ///
29 /// **Example:**
30 /// ```rust
31 /// let x = &x;
32 /// ```
33 declare_clippy_lint! {
34     pub SHADOW_SAME,
35     restriction,
36     "rebinding a name to itself, e.g. `let mut x = &mut x`"
37 }
38
39 /// **What it does:** Checks for bindings that shadow other bindings already in
40 /// scope, while reusing the original value.
41 ///
42 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
43 /// code. Still, some argue that name shadowing like this hurts readability,
44 /// because a value may be bound to different things depending on position in
45 /// the code.
46 ///
47 /// **Known problems:** This lint, as the other shadowing related lints,
48 /// currently only catches very simple patterns.
49 ///
50 /// **Example:**
51 /// ```rust
52 /// let x = x + 1;
53 /// ```
54 /// use different variable name:
55 /// ```rust
56 /// let y = x + 1;
57 /// ```
58 declare_clippy_lint! {
59 pub SHADOW_REUSE,
60 restriction,
61 "rebinding a name to an expression that re-uses the original value, e.g. \
62  `let x = x + 1`"
63 }
64
65 /// **What it does:** Checks for bindings that shadow other bindings already in
66 /// scope, either without a initialization or with one that does not even use
67 /// the original value.
68 ///
69 /// **Why is this bad?** Name shadowing can hurt readability, especially in
70 /// large code bases, because it is easy to lose track of the active binding at
71 /// any place in the code. This can be alleviated by either giving more specific
72 /// names to bindings or introducing more scopes to contain the bindings.
73 ///
74 /// **Known problems:** This lint, as the other shadowing related lints,
75 /// currently only catches very simple patterns.
76 ///
77 /// **Example:**
78 /// ```rust
79 /// let x = y;
80 /// let x = z; // shadows the earlier binding
81 /// ```
82 declare_clippy_lint! {
83     pub SHADOW_UNRELATED,
84     pedantic,
85     "rebinding a name without even using the original value"
86 }
87
88 #[derive(Copy, Clone)]
89 pub struct Pass;
90
91 impl LintPass for Pass {
92     fn get_lints(&self) -> LintArray {
93         lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
94     }
95 }
96
97 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
98     fn check_fn(
99         &mut self,
100         cx: &LateContext<'a, 'tcx>,
101         _: FnKind<'tcx>,
102         decl: &'tcx FnDecl,
103         body: &'tcx Body,
104         _: Span,
105         _: NodeId,
106     ) {
107         if in_external_macro(cx.sess(), body.value.span) {
108             return;
109         }
110         check_fn(cx, decl, body);
111     }
112 }
113
114 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
115     let mut bindings = Vec::new();
116     for arg in iter_input_pats(decl, body) {
117         if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
118             bindings.push((ident.name, ident.span))
119         }
120     }
121     check_expr(cx, &body.value, &mut bindings);
122 }
123
124 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
125     let len = bindings.len();
126     for stmt in &block.stmts {
127         match stmt.node {
128             StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
129             StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
130         }
131     }
132     if let Some(ref o) = block.expr {
133         check_expr(cx, o, bindings);
134     }
135     bindings.truncate(len);
136 }
137
138 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
139     if in_external_macro(cx.sess(), decl.span) {
140         return;
141     }
142     if higher::is_from_for_desugar(decl) {
143         return;
144     }
145     if let DeclKind::Local(ref local) = decl.node {
146         let Local {
147             ref pat,
148             ref ty,
149             ref init,
150             span,
151             ..
152         } = **local;
153         if let Some(ref t) = *ty {
154             check_ty(cx, t, bindings)
155         }
156         if let Some(ref o) = *init {
157             check_expr(cx, o, bindings);
158             check_pat(cx, pat, Some(o), span, bindings);
159         } else {
160             check_pat(cx, pat, None, span, bindings);
161         }
162     }
163 }
164
165 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
166     let var_ty = cx.tables.node_id_to_type(pat_id);
167     match var_ty.sty {
168         ty::Adt(..) => false,
169         _ => true,
170     }
171 }
172
173 fn check_pat<'a, 'tcx>(
174     cx: &LateContext<'a, 'tcx>,
175     pat: &'tcx Pat,
176     init: Option<&'tcx Expr>,
177     span: Span,
178     bindings: &mut Vec<(Name, Span)>,
179 ) {
180     // TODO: match more stuff / destructuring
181     match pat.node {
182         PatKind::Binding(_, _, ident, ref inner) => {
183             let name = ident.name;
184             if is_binding(cx, pat.hir_id) {
185                 let mut new_binding = true;
186                 for tup in bindings.iter_mut() {
187                     if tup.0 == name {
188                         lint_shadow(cx, name, span, pat.span, init, tup.1);
189                         tup.1 = ident.span;
190                         new_binding = false;
191                         break;
192                     }
193                 }
194                 if new_binding {
195                     bindings.push((name, ident.span));
196                 }
197             }
198             if let Some(ref p) = *inner {
199                 check_pat(cx, p, init, span, bindings);
200             }
201         },
202         PatKind::Struct(_, ref pfields, _) => {
203             if let Some(init_struct) = init {
204                 if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
205                     for field in pfields {
206                         let name = field.node.ident.name;
207                         let efield = efields.iter().find(|f| f.ident.name == name).map(|f| &*f.expr);
208                         check_pat(cx, &field.node.pat, efield, span, bindings);
209                     }
210                 } else {
211                     for field in pfields {
212                         check_pat(cx, &field.node.pat, init, span, bindings);
213                     }
214                 }
215             } else {
216                 for field in pfields {
217                     check_pat(cx, &field.node.pat, None, span, bindings);
218                 }
219             }
220         },
221         PatKind::Tuple(ref inner, _) => {
222             if let Some(init_tup) = init {
223                 if let ExprKind::Tup(ref tup) = init_tup.node {
224                     for (i, p) in inner.iter().enumerate() {
225                         check_pat(cx, p, Some(&tup[i]), p.span, bindings);
226                     }
227                 } else {
228                     for p in inner {
229                         check_pat(cx, p, init, span, bindings);
230                     }
231                 }
232             } else {
233                 for p in inner {
234                     check_pat(cx, p, None, span, bindings);
235                 }
236             }
237         },
238         PatKind::Box(ref inner) => {
239             if let Some(initp) = init {
240                 if let ExprKind::Box(ref inner_init) = initp.node {
241                     check_pat(cx, inner, Some(&**inner_init), span, bindings);
242                 } else {
243                     check_pat(cx, inner, init, span, bindings);
244                 }
245             } else {
246                 check_pat(cx, inner, init, span, bindings);
247             }
248         },
249         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
250         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
251         _ => (),
252     }
253 }
254
255 fn lint_shadow<'a, 'tcx: 'a>(
256     cx: &LateContext<'a, 'tcx>,
257     name: Name,
258     span: Span,
259     pattern_span: Span,
260     init: Option<&'tcx Expr>,
261     prev_span: Span,
262 ) {
263     if let Some(expr) = init {
264         if is_self_shadow(name, expr) {
265             span_lint_and_then(
266                 cx,
267                 SHADOW_SAME,
268                 span,
269                 &format!(
270                     "`{}` is shadowed by itself in `{}`",
271                     snippet(cx, pattern_span, "_"),
272                     snippet(cx, expr.span, "..")
273                 ),
274                 |db| {
275                     db.span_note(prev_span, "previous binding is here");
276                 },
277             );
278         } else if contains_name(name, expr) {
279             span_lint_and_then(
280                 cx,
281                 SHADOW_REUSE,
282                 pattern_span,
283                 &format!(
284                     "`{}` is shadowed by `{}` which reuses the original value",
285                     snippet(cx, pattern_span, "_"),
286                     snippet(cx, expr.span, "..")
287                 ),
288                 |db| {
289                     db.span_note(expr.span, "initialization happens here");
290                     db.span_note(prev_span, "previous binding is here");
291                 },
292             );
293         } else {
294             span_lint_and_then(
295                 cx,
296                 SHADOW_UNRELATED,
297                 pattern_span,
298                 &format!(
299                     "`{}` is shadowed by `{}`",
300                     snippet(cx, pattern_span, "_"),
301                     snippet(cx, expr.span, "..")
302                 ),
303                 |db| {
304                     db.span_note(expr.span, "initialization happens here");
305                     db.span_note(prev_span, "previous binding is here");
306                 },
307             );
308         }
309     } else {
310         span_lint_and_then(
311             cx,
312             SHADOW_UNRELATED,
313             span,
314             &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
315             |db| {
316                 db.span_note(prev_span, "previous binding is here");
317             },
318         );
319     }
320 }
321
322 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
323     if in_external_macro(cx.sess(), expr.span) {
324         return;
325     }
326     match expr.node {
327         ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
328             check_expr(cx, e, bindings)
329         },
330         ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
331         // ExprKind::Call
332         // ExprKind::MethodCall
333         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => {
334             for e in v {
335                 check_expr(cx, e, bindings)
336             }
337         },
338         ExprKind::If(ref cond, ref then, ref otherwise) => {
339             check_expr(cx, cond, bindings);
340             check_expr(cx, &**then, bindings);
341             if let Some(ref o) = *otherwise {
342                 check_expr(cx, o, bindings);
343             }
344         },
345         ExprKind::While(ref cond, ref block, _) => {
346             check_expr(cx, cond, bindings);
347             check_block(cx, block, bindings);
348         },
349         ExprKind::Match(ref init, ref arms, _) => {
350             check_expr(cx, init, bindings);
351             let len = bindings.len();
352             for arm in arms {
353                 for pat in &arm.pats {
354                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
355                     // This is ugly, but needed to get the right type
356                     if let Some(ref guard) = arm.guard {
357                         match guard {
358                             Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
359                         }
360                     }
361                     check_expr(cx, &arm.body, bindings);
362                     bindings.truncate(len);
363                 }
364             }
365         },
366         _ => (),
367     }
368 }
369
370 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
371     match ty.node {
372         TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
373         TyKind::Array(ref fty, ref anon_const) => {
374             check_ty(cx, fty, bindings);
375             check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings);
376         },
377         TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
378             check_ty(cx, mty, bindings)
379         },
380         TyKind::Tup(ref tup) => {
381             for t in tup {
382                 check_ty(cx, t, bindings)
383             }
384         },
385         TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings),
386         _ => (),
387     }
388 }
389
390 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
391     match expr.node {
392         ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
393         ExprKind::Block(ref block, _) => {
394             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
395         },
396         ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
397         ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
398         _ => false,
399     }
400 }
401
402 fn path_eq_name(name: Name, path: &Path) -> bool {
403     !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
404 }