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