]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Remove all copyright license headers
[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
87 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
88     fn check_fn(
89         &mut self,
90         cx: &LateContext<'a, 'tcx>,
91         _: FnKind<'tcx>,
92         decl: &'tcx FnDecl,
93         body: &'tcx Body,
94         _: Span,
95         _: NodeId,
96     ) {
97         if in_external_macro(cx.sess(), body.value.span) {
98             return;
99         }
100         check_fn(cx, decl, body);
101     }
102 }
103
104 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
105     let mut bindings = Vec::new();
106     for arg in iter_input_pats(decl, body) {
107         if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
108             bindings.push((ident.name, ident.span))
109         }
110     }
111     check_expr(cx, &body.value, &mut bindings);
112 }
113
114 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
115     let len = bindings.len();
116     for stmt in &block.stmts {
117         match stmt.node {
118             StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
119             StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
120         }
121     }
122     if let Some(ref o) = block.expr {
123         check_expr(cx, o, bindings);
124     }
125     bindings.truncate(len);
126 }
127
128 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
129     if in_external_macro(cx.sess(), decl.span) {
130         return;
131     }
132     if higher::is_from_for_desugar(decl) {
133         return;
134     }
135     if let DeclKind::Local(ref local) = decl.node {
136         let Local {
137             ref pat,
138             ref ty,
139             ref init,
140             span,
141             ..
142         } = **local;
143         if let Some(ref t) = *ty {
144             check_ty(cx, t, bindings)
145         }
146         if let Some(ref o) = *init {
147             check_expr(cx, o, bindings);
148             check_pat(cx, pat, Some(o), span, bindings);
149         } else {
150             check_pat(cx, pat, None, span, bindings);
151         }
152     }
153 }
154
155 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
156     let var_ty = cx.tables.node_id_to_type(pat_id);
157     match var_ty.sty {
158         ty::Adt(..) => false,
159         _ => true,
160     }
161 }
162
163 fn check_pat<'a, 'tcx>(
164     cx: &LateContext<'a, 'tcx>,
165     pat: &'tcx Pat,
166     init: Option<&'tcx Expr>,
167     span: Span,
168     bindings: &mut Vec<(Name, Span)>,
169 ) {
170     // TODO: match more stuff / destructuring
171     match pat.node {
172         PatKind::Binding(_, _, ident, ref inner) => {
173             let name = ident.name;
174             if is_binding(cx, pat.hir_id) {
175                 let mut new_binding = true;
176                 for tup in bindings.iter_mut() {
177                     if tup.0 == name {
178                         lint_shadow(cx, name, span, pat.span, init, tup.1);
179                         tup.1 = ident.span;
180                         new_binding = false;
181                         break;
182                     }
183                 }
184                 if new_binding {
185                     bindings.push((name, ident.span));
186                 }
187             }
188             if let Some(ref p) = *inner {
189                 check_pat(cx, p, init, span, bindings);
190             }
191         },
192         PatKind::Struct(_, ref pfields, _) => {
193             if let Some(init_struct) = init {
194                 if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
195                     for field in pfields {
196                         let name = field.node.ident.name;
197                         let efield = efields.iter().find(|f| f.ident.name == name).map(|f| &*f.expr);
198                         check_pat(cx, &field.node.pat, efield, span, bindings);
199                     }
200                 } else {
201                     for field in pfields {
202                         check_pat(cx, &field.node.pat, init, span, bindings);
203                     }
204                 }
205             } else {
206                 for field in pfields {
207                     check_pat(cx, &field.node.pat, None, span, bindings);
208                 }
209             }
210         },
211         PatKind::Tuple(ref inner, _) => {
212             if let Some(init_tup) = init {
213                 if let ExprKind::Tup(ref tup) = init_tup.node {
214                     for (i, p) in inner.iter().enumerate() {
215                         check_pat(cx, p, Some(&tup[i]), p.span, bindings);
216                     }
217                 } else {
218                     for p in inner {
219                         check_pat(cx, p, init, span, bindings);
220                     }
221                 }
222             } else {
223                 for p in inner {
224                     check_pat(cx, p, None, span, bindings);
225                 }
226             }
227         },
228         PatKind::Box(ref inner) => {
229             if let Some(initp) = init {
230                 if let ExprKind::Box(ref inner_init) = initp.node {
231                     check_pat(cx, inner, Some(&**inner_init), span, bindings);
232                 } else {
233                     check_pat(cx, inner, init, span, bindings);
234                 }
235             } else {
236                 check_pat(cx, inner, init, span, bindings);
237             }
238         },
239         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
240         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
241         _ => (),
242     }
243 }
244
245 fn lint_shadow<'a, 'tcx: 'a>(
246     cx: &LateContext<'a, 'tcx>,
247     name: Name,
248     span: Span,
249     pattern_span: Span,
250     init: Option<&'tcx Expr>,
251     prev_span: Span,
252 ) {
253     if let Some(expr) = init {
254         if is_self_shadow(name, expr) {
255             span_lint_and_then(
256                 cx,
257                 SHADOW_SAME,
258                 span,
259                 &format!(
260                     "`{}` is shadowed by itself in `{}`",
261                     snippet(cx, pattern_span, "_"),
262                     snippet(cx, expr.span, "..")
263                 ),
264                 |db| {
265                     db.span_note(prev_span, "previous binding is here");
266                 },
267             );
268         } else if contains_name(name, expr) {
269             span_lint_and_then(
270                 cx,
271                 SHADOW_REUSE,
272                 pattern_span,
273                 &format!(
274                     "`{}` is shadowed by `{}` which reuses the original value",
275                     snippet(cx, pattern_span, "_"),
276                     snippet(cx, expr.span, "..")
277                 ),
278                 |db| {
279                     db.span_note(expr.span, "initialization happens here");
280                     db.span_note(prev_span, "previous binding is here");
281                 },
282             );
283         } else {
284             span_lint_and_then(
285                 cx,
286                 SHADOW_UNRELATED,
287                 pattern_span,
288                 &format!(
289                     "`{}` is shadowed by `{}`",
290                     snippet(cx, pattern_span, "_"),
291                     snippet(cx, expr.span, "..")
292                 ),
293                 |db| {
294                     db.span_note(expr.span, "initialization happens here");
295                     db.span_note(prev_span, "previous binding is here");
296                 },
297             );
298         }
299     } else {
300         span_lint_and_then(
301             cx,
302             SHADOW_UNRELATED,
303             span,
304             &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
305             |db| {
306                 db.span_note(prev_span, "previous binding is here");
307             },
308         );
309     }
310 }
311
312 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
313     if in_external_macro(cx.sess(), expr.span) {
314         return;
315     }
316     match expr.node {
317         ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
318             check_expr(cx, e, bindings)
319         },
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::If(ref cond, ref then, ref otherwise) => {
329             check_expr(cx, cond, bindings);
330             check_expr(cx, &**then, bindings);
331             if let Some(ref o) = *otherwise {
332                 check_expr(cx, o, bindings);
333             }
334         },
335         ExprKind::While(ref cond, ref block, _) => {
336             check_expr(cx, cond, bindings);
337             check_block(cx, block, bindings);
338         },
339         ExprKind::Match(ref init, ref arms, _) => {
340             check_expr(cx, init, bindings);
341             let len = bindings.len();
342             for arm in arms {
343                 for pat in &arm.pats {
344                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
345                     // This is ugly, but needed to get the right type
346                     if let Some(ref guard) = arm.guard {
347                         match guard {
348                             Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
349                         }
350                     }
351                     check_expr(cx, &arm.body, bindings);
352                     bindings.truncate(len);
353                 }
354             }
355         },
356         _ => (),
357     }
358 }
359
360 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
361     match ty.node {
362         TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
363         TyKind::Array(ref fty, ref anon_const) => {
364             check_ty(cx, fty, bindings);
365             check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
366         },
367         TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
368             check_ty(cx, mty, bindings)
369         },
370         TyKind::Tup(ref tup) => {
371             for t in tup {
372                 check_ty(cx, t, bindings)
373             }
374         },
375         TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
376         _ => (),
377     }
378 }
379
380 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
381     match expr.node {
382         ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
383         ExprKind::Block(ref block, _) => {
384             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
385         },
386         ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
387         ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
388         _ => false,
389     }
390 }
391
392 fn path_eq_name(name: Name, path: &Path) -> bool {
393     !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
394 }