]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Fix lines that exceed max width manually
[rust.git] / clippy_lints / src / shadow.rs
1 use reexport::*;
2 use rustc::lint::*;
3 use rustc::hir::*;
4 use rustc::hir::intravisit::FnKind;
5 use rustc::ty;
6 use syntax::codemap::Span;
7 use utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then};
8
9 /// **What it does:** Checks for bindings that shadow other bindings already in
10 /// scope, while just changing reference level or mutability.
11 ///
12 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
13 /// code. Still, some may opt to avoid it in their code base, they can set this
14 /// lint to `Warn`.
15 ///
16 /// **Known problems:** This lint, as the other shadowing related lints,
17 /// currently only catches very simple patterns.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// let x = &x;
22 /// ```
23 declare_lint! {
24     pub SHADOW_SAME,
25     Allow,
26     "rebinding a name to itself, e.g. `let mut x = &mut x`"
27 }
28
29 /// **What it does:** Checks for bindings that shadow other bindings already in
30 /// scope, while reusing the original value.
31 ///
32 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
33 /// code. Still, some argue that name shadowing like this hurts readability,
34 /// because a value may be bound to different things depending on position in
35 /// the code.
36 ///
37 /// **Known problems:** This lint, as the other shadowing related lints,
38 /// currently only catches very simple patterns.
39 ///
40 /// **Example:**
41 /// ```rust
42 /// let x = x + 1;
43 /// ```
44 declare_lint! {
45     pub SHADOW_REUSE,
46     Allow,
47     "rebinding a name to an expression that re-uses the original value, e.g. \
48      `let x = x + 1`"
49 }
50
51 /// **What it does:** Checks for bindings that shadow other bindings already in
52 /// scope, either without a initialization or with one that does not even use
53 /// the original value.
54 ///
55 /// **Why is this bad?** Name shadowing can hurt readability, especially in
56 /// large code bases, because it is easy to lose track of the active binding at
57 /// any place in the code. This can be alleviated by either giving more specific
58 /// names to bindings ore introducing more scopes to contain the bindings.
59 ///
60 /// **Known problems:** This lint, as the other shadowing related lints,
61 /// currently only catches very simple patterns.
62 ///
63 /// **Example:**
64 /// ```rust
65 /// let x = y; let x = z; // shadows the earlier binding
66 /// ```
67 declare_lint! {
68     pub SHADOW_UNRELATED,
69     Allow,
70     "rebinding a name without even using the original value"
71 }
72
73 #[derive(Copy, Clone)]
74 pub struct Pass;
75
76 impl LintPass for Pass {
77     fn get_lints(&self) -> LintArray {
78         lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
79     }
80 }
81
82 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
83     fn check_fn(
84         &mut self,
85         cx: &LateContext<'a, 'tcx>,
86         _: FnKind<'tcx>,
87         decl: &'tcx FnDecl,
88         body: &'tcx Body,
89         _: Span,
90         _: NodeId,
91     ) {
92         if in_external_macro(cx, body.value.span) {
93             return;
94         }
95         check_fn(cx, decl, body);
96     }
97 }
98
99 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
100     let mut bindings = Vec::new();
101     for arg in iter_input_pats(decl, body) {
102         if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
103             bindings.push((ident.node, ident.span))
104         }
105     }
106     check_expr(cx, &body.value, &mut bindings);
107 }
108
109 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
110     let len = bindings.len();
111     for stmt in &block.stmts {
112         match stmt.node {
113             StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
114             StmtExpr(ref e, _) | StmtSemi(ref e, _) => check_expr(cx, e, bindings),
115         }
116     }
117     if let Some(ref o) = block.expr {
118         check_expr(cx, o, bindings);
119     }
120     bindings.truncate(len);
121 }
122
123 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
124     if in_external_macro(cx, decl.span) {
125         return;
126     }
127     if higher::is_from_for_desugar(decl) {
128         return;
129     }
130     if let DeclLocal(ref local) = decl.node {
131         let Local {
132             ref pat,
133             ref ty,
134             ref init,
135             span,
136             ..
137         } = **local;
138         if let Some(ref t) = *ty {
139             check_ty(cx, t, bindings)
140         }
141         if let Some(ref o) = *init {
142             check_expr(cx, o, bindings);
143             check_pat(cx, pat, Some(o), span, bindings);
144         } else {
145             check_pat(cx, pat, None, span, bindings);
146         }
147     }
148 }
149
150 fn is_binding(cx: &LateContext, pat_id: HirId) -> bool {
151     let var_ty = cx.tables.node_id_to_type(pat_id);
152     match var_ty.sty {
153         ty::TyAdt(..) => false,
154         _ => true,
155     }
156 }
157
158 fn check_pat<'a, 'tcx>(
159     cx: &LateContext<'a, 'tcx>,
160     pat: &'tcx Pat,
161     init: Option<&'tcx Expr>,
162     span: Span,
163     bindings: &mut Vec<(Name, Span)>,
164 ) {
165     // TODO: match more stuff / destructuring
166     match pat.node {
167         PatKind::Binding(_, _, ref ident, ref inner) => {
168             let name = ident.node;
169             if is_binding(cx, pat.hir_id) {
170                 let mut new_binding = true;
171                 for tup in bindings.iter_mut() {
172                     if tup.0 == name {
173                         lint_shadow(cx, name, span, pat.span, init, tup.1);
174                         tup.1 = ident.span;
175                         new_binding = false;
176                         break;
177                     }
178                 }
179                 if new_binding {
180                     bindings.push((name, ident.span));
181                 }
182             }
183             if let Some(ref p) = *inner {
184                 check_pat(cx, p, init, span, bindings);
185             }
186         },
187         PatKind::Struct(_, ref pfields, _) => if let Some(init_struct) = init {
188             if let ExprStruct(_, ref efields, _) = init_struct.node {
189                 for field in pfields {
190                     let name = field.node.name;
191                     let efield = efields
192                         .iter()
193                         .find(|f| f.name.node == name)
194                         .map(|f| &*f.expr);
195                     check_pat(cx, &field.node.pat, efield, span, bindings);
196                 }
197             } else {
198                 for field in pfields {
199                     check_pat(cx, &field.node.pat, init, span, bindings);
200                 }
201             }
202         } else {
203             for field in pfields {
204                 check_pat(cx, &field.node.pat, None, span, bindings);
205             }
206         },
207         PatKind::Tuple(ref inner, _) => if let Some(init_tup) = init {
208             if let ExprTup(ref tup) = init_tup.node {
209                 for (i, p) in inner.iter().enumerate() {
210                     check_pat(cx, p, Some(&tup[i]), p.span, bindings);
211                 }
212             } else {
213                 for p in inner {
214                     check_pat(cx, p, init, span, bindings);
215                 }
216             }
217         } else {
218             for p in inner {
219                 check_pat(cx, p, None, span, bindings);
220             }
221         },
222         PatKind::Box(ref inner) => if let Some(initp) = init {
223             if let ExprBox(ref inner_init) = initp.node {
224                 check_pat(cx, inner, Some(&**inner_init), span, bindings);
225             } else {
226                 check_pat(cx, inner, init, span, bindings);
227             }
228         } else {
229             check_pat(cx, inner, init, span, bindings);
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, expr.span) {
306         return;
307     }
308     match expr.node {
309         ExprUnary(_, ref e) | ExprField(ref e, _) | ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) => {
310             check_expr(cx, e, bindings)
311         },
312         ExprBlock(ref block) | ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
313         // ExprCall
314         // ExprMethodCall
315         ExprArray(ref v) | ExprTup(ref v) => for e in v {
316             check_expr(cx, e, bindings)
317         },
318         ExprIf(ref cond, ref then, ref otherwise) => {
319             check_expr(cx, cond, bindings);
320             check_expr(cx, &**then, bindings);
321             if let Some(ref o) = *otherwise {
322                 check_expr(cx, o, bindings);
323             }
324         },
325         ExprWhile(ref cond, ref block, _) => {
326             check_expr(cx, cond, bindings);
327             check_block(cx, block, bindings);
328         },
329         ExprMatch(ref init, ref arms, _) => {
330             check_expr(cx, init, bindings);
331             let len = bindings.len();
332             for arm in arms {
333                 for pat in &arm.pats {
334                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
335                     // This is ugly, but needed to get the right type
336                     if let Some(ref guard) = arm.guard {
337                         check_expr(cx, guard, bindings);
338                     }
339                     check_expr(cx, &arm.body, bindings);
340                     bindings.truncate(len);
341                 }
342             }
343         },
344         _ => (),
345     }
346 }
347
348 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
349     match ty.node {
350         TySlice(ref sty) => check_ty(cx, sty, bindings),
351         TyArray(ref fty, body_id) => {
352             check_ty(cx, fty, bindings);
353             check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings);
354         },
355         TyPtr(MutTy { ty: ref mty, .. }) | TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
356         TyTup(ref tup) => for t in tup {
357             check_ty(cx, t, bindings)
358         },
359         TyTypeof(body_id) => check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings),
360         _ => (),
361     }
362 }
363
364 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
365     match expr.node {
366         ExprBox(ref inner) | ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
367         ExprBlock(ref block) => {
368             block.stmts.is_empty()
369                 && block
370                     .expr
371                     .as_ref()
372                     .map_or(false, |e| is_self_shadow(name, e))
373         },
374         ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
375         ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
376         _ => false,
377     }
378 }
379
380 fn path_eq_name(name: Name, path: &Path) -> bool {
381     !path.is_global() && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
382 }