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