]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[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
11 use crate::reexport::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc::hir::*;
15 use crate::rustc::hir::intravisit::FnKind;
16 use crate::rustc::ty;
17 use crate::syntax::source_map::Span;
18 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
19
20 /// **What it does:** Checks for bindings that shadow other bindings already in
21 /// scope, while just changing reference level or mutability.
22 ///
23 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
24 /// code. Still, some may opt to avoid it in their code base, they can set this
25 /// lint to `Warn`.
26 ///
27 /// **Known problems:** This lint, as the other shadowing related lints,
28 /// currently only catches very simple patterns.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// let x = &x;
33 /// ```
34 declare_clippy_lint! {
35     pub SHADOW_SAME,
36     restriction,
37     "rebinding a name to itself, e.g. `let mut x = &mut x`"
38 }
39
40 /// **What it does:** Checks for bindings that shadow other bindings already in
41 /// scope, while reusing the original value.
42 ///
43 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
44 /// code. Still, some argue that name shadowing like this hurts readability,
45 /// because a value may be bound to different things depending on position in
46 /// the code.
47 ///
48 /// **Known problems:** This lint, as the other shadowing related lints,
49 /// currently only catches very simple patterns.
50 ///
51 /// **Example:**
52 /// ```rust
53 /// let x = x + 1;
54 /// ```
55 /// use different variable name:
56 /// ```rust
57 /// let y = x + 1;
58 /// ```
59 declare_clippy_lint! {
60     pub SHADOW_REUSE,
61     restriction,
62     "rebinding a name to an expression that re-uses the original value, e.g. \
63      `let x = x + 1`"
64 }
65
66 /// **What it does:** Checks for bindings that shadow other bindings already in
67 /// scope, either without a initialization or with one that does not even use
68 /// the original value.
69 ///
70 /// **Why is this bad?** Name shadowing can hurt readability, especially in
71 /// large code bases, because it is easy to lose track of the active binding at
72 /// any place in the code. This can be alleviated by either giving more specific
73 /// names to bindings or introducing more scopes to contain the bindings.
74 ///
75 /// **Known problems:** This lint, as the other shadowing related lints,
76 /// currently only catches very simple patterns.
77 ///
78 /// **Example:**
79 /// ```rust
80 /// let x = y; 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, _) => if let Some(init_struct) = init {
203             if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
204                 for field in pfields {
205                     let name = field.node.ident.name;
206                     let efield = efields
207                         .iter()
208                         .find(|f| f.ident.name == name)
209                         .map(|f| &*f.expr);
210                     check_pat(cx, &field.node.pat, efield, span, bindings);
211                 }
212             } else {
213                 for field in pfields {
214                     check_pat(cx, &field.node.pat, init, span, bindings);
215                 }
216             }
217         } else {
218             for field in pfields {
219                 check_pat(cx, &field.node.pat, None, span, bindings);
220             }
221         },
222         PatKind::Tuple(ref inner, _) => 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         PatKind::Box(ref inner) => if let Some(initp) = init {
238             if let ExprKind::Box(ref inner_init) = initp.node {
239                 check_pat(cx, inner, Some(&**inner_init), span, bindings);
240             } else {
241                 check_pat(cx, inner, init, span, bindings);
242             }
243         } else {
244             check_pat(cx, inner, init, span, bindings);
245         },
246         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
247         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
248         _ => (),
249     }
250 }
251
252 fn lint_shadow<'a, 'tcx: 'a>(
253     cx: &LateContext<'a, 'tcx>,
254     name: Name,
255     span: Span,
256     pattern_span: Span,
257     init: Option<&'tcx Expr>,
258     prev_span: Span,
259 ) {
260     if let Some(expr) = init {
261         if is_self_shadow(name, expr) {
262             span_lint_and_then(
263                 cx,
264                 SHADOW_SAME,
265                 span,
266                 &format!(
267                     "`{}` is shadowed by itself in `{}`",
268                     snippet(cx, pattern_span, "_"),
269                     snippet(cx, expr.span, "..")
270                 ),
271                 |db| {
272                     db.span_note(prev_span, "previous binding is here");
273                 },
274             );
275         } else if contains_name(name, expr) {
276             span_lint_and_then(
277                 cx,
278                 SHADOW_REUSE,
279                 pattern_span,
280                 &format!(
281                     "`{}` is shadowed by `{}` which reuses the original value",
282                     snippet(cx, pattern_span, "_"),
283                     snippet(cx, expr.span, "..")
284                 ),
285                 |db| {
286                     db.span_note(expr.span, "initialization happens here");
287                     db.span_note(prev_span, "previous binding is here");
288                 },
289             );
290         } else {
291             span_lint_and_then(
292                 cx,
293                 SHADOW_UNRELATED,
294                 pattern_span,
295                 &format!(
296                     "`{}` is shadowed by `{}`",
297                     snippet(cx, pattern_span, "_"),
298                     snippet(cx, expr.span, "..")
299                 ),
300                 |db| {
301                     db.span_note(expr.span, "initialization happens here");
302                     db.span_note(prev_span, "previous binding is here");
303                 },
304             );
305         }
306     } else {
307         span_lint_and_then(
308             cx,
309             SHADOW_UNRELATED,
310             span,
311             &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
312             |db| {
313                 db.span_note(prev_span, "previous binding is here");
314             },
315         );
316     }
317 }
318
319 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
320     if in_external_macro(cx.sess(), expr.span) {
321         return;
322     }
323     match expr.node {
324         ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
325             check_expr(cx, e, bindings)
326         },
327         ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
328         // ExprKind::Call
329         // ExprKind::MethodCall
330         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => for e in v {
331             check_expr(cx, e, bindings)
332         },
333         ExprKind::If(ref cond, ref then, ref otherwise) => {
334             check_expr(cx, cond, bindings);
335             check_expr(cx, &**then, bindings);
336             if let Some(ref o) = *otherwise {
337                 check_expr(cx, o, bindings);
338             }
339         },
340         ExprKind::While(ref cond, ref block, _) => {
341             check_expr(cx, cond, bindings);
342             check_block(cx, block, bindings);
343         },
344         ExprKind::Match(ref init, ref arms, _) => {
345             check_expr(cx, init, bindings);
346             let len = bindings.len();
347             for arm in arms {
348                 for pat in &arm.pats {
349                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
350                     // This is ugly, but needed to get the right type
351                     if let Some(ref guard) = arm.guard {
352                         match guard {
353                             Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
354                         }
355                     }
356                     check_expr(cx, &arm.body, bindings);
357                     bindings.truncate(len);
358                 }
359             }
360         },
361         _ => (),
362     }
363 }
364
365 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
366     match ty.node {
367         TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
368         TyKind::Array(ref fty, ref anon_const) => {
369             check_ty(cx, fty, bindings);
370             check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings);
371         },
372         TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
373         TyKind::Tup(ref tup) => for t in tup {
374             check_ty(cx, t, bindings)
375         },
376         TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings),
377         _ => (),
378     }
379 }
380
381 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
382     match expr.node {
383         ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
384         ExprKind::Block(ref block, _) => {
385             block.stmts.is_empty()
386                 && block
387                     .expr
388                     .as_ref()
389                     .map_or(false, |e| is_self_shadow(name, e))
390         },
391         ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
392         ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
393         _ => false,
394     }
395 }
396
397 fn path_eq_name(name: Name, path: &Path) -> bool {
398     !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
399 }