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