]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Merge pull request #1256 from Manishearth/allow_map_or
[rust.git] / clippy_lints / src / shadow.rs
1 use reexport::*;
2 use rustc::lint::*;
3 use rustc::hir::def::Def;
4 use rustc::hir::*;
5 use rustc::hir::intravisit::{Visitor, FnKind};
6 use std::ops::Deref;
7 use syntax::codemap::Span;
8 use utils::{higher, in_external_macro, snippet, span_lint_and_then};
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_lint! {
25     pub SHADOW_SAME,
26     Allow,
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 declare_lint! {
46     pub SHADOW_REUSE,
47     Allow,
48     "rebinding a name to an expression that re-uses the original value, e.g. \
49      `let x = x + 1`"
50 }
51
52 /// **What it does:** Checks for bindings that shadow other bindings already in
53 /// scope, either without a initialization or with one that does not even use
54 /// the original value.
55 ///
56 /// **Why is this bad?** Name shadowing can hurt readability, especially in
57 /// large code bases, because it is easy to lose track of the active binding at
58 /// any place in the code. This can be alleviated by either giving more specific
59 /// names to bindings ore introducing more scopes to contain the bindings.
60 ///
61 /// **Known problems:** This lint, as the other shadowing related lints,
62 /// currently only catches very simple patterns.
63 ///
64 /// **Example:**
65 /// ```rust
66 /// let x = y; let x = z; // shadows the earlier binding
67 /// ```
68 declare_lint! {
69     pub SHADOW_UNRELATED,
70     Allow,
71     "rebinding a name without even using the original value"
72 }
73
74 #[derive(Copy, Clone)]
75 pub struct Pass;
76
77 impl LintPass for Pass {
78     fn get_lints(&self) -> LintArray {
79         lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
80     }
81 }
82
83 impl LateLintPass for Pass {
84     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, block: &Block, _: Span, _: NodeId) {
85         if in_external_macro(cx, block.span) {
86             return;
87         }
88         check_fn(cx, decl, block);
89     }
90 }
91
92 fn check_fn(cx: &LateContext, decl: &FnDecl, block: &Block) {
93     let mut bindings = Vec::new();
94     for arg in &decl.inputs {
95         if let PatKind::Binding(_, ident, _) = arg.pat.node {
96             bindings.push((ident.node, ident.span))
97         }
98     }
99     check_block(cx, block, &mut bindings);
100 }
101
102 fn check_block(cx: &LateContext, block: &Block, bindings: &mut Vec<(Name, Span)>) {
103     let len = bindings.len();
104     for stmt in &block.stmts {
105         match stmt.node {
106             StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
107             StmtExpr(ref e, _) |
108             StmtSemi(ref e, _) => check_expr(cx, e, bindings),
109         }
110     }
111     if let Some(ref o) = block.expr {
112         check_expr(cx, o, bindings);
113     }
114     bindings.truncate(len);
115 }
116
117 fn check_decl(cx: &LateContext, decl: &Decl, bindings: &mut Vec<(Name, Span)>) {
118     if in_external_macro(cx, decl.span) {
119         return;
120     }
121     if higher::is_from_for_desugar(decl) {
122         return;
123     }
124     if let DeclLocal(ref local) = decl.node {
125         let Local { ref pat, ref ty, ref init, span, .. } = **local;
126         if let Some(ref t) = *ty {
127             check_ty(cx, t, bindings)
128         }
129         if let Some(ref o) = *init {
130             check_expr(cx, o, bindings);
131             check_pat(cx, pat, &Some(o), span, bindings);
132         } else {
133             check_pat(cx, pat, &None, span, bindings);
134         }
135     }
136 }
137
138 fn is_binding(cx: &LateContext, pat: &Pat) -> bool {
139     match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
140         Some(Def::Variant(..)) |
141         Some(Def::Struct(..)) => false,
142         _ => true,
143     }
144 }
145
146 fn check_pat(cx: &LateContext, pat: &Pat, init: &Option<&Expr>, span: Span, bindings: &mut Vec<(Name, Span)>) {
147     // TODO: match more stuff / destructuring
148     match pat.node {
149         PatKind::Binding(_, ref ident, ref inner) => {
150             let name = ident.node;
151             if is_binding(cx, pat) {
152                 let mut new_binding = true;
153                 for tup in bindings.iter_mut() {
154                     if tup.0 == name {
155                         lint_shadow(cx, name, span, pat.span, init, tup.1);
156                         tup.1 = ident.span;
157                         new_binding = false;
158                         break;
159                     }
160                 }
161                 if new_binding {
162                     bindings.push((name, ident.span));
163                 }
164             }
165             if let Some(ref p) = *inner {
166                 check_pat(cx, p, init, span, bindings);
167             }
168         }
169         PatKind::Struct(_, ref pfields, _) => {
170             if let Some(init_struct) = *init {
171                 if let ExprStruct(_, ref efields, _) = init_struct.node {
172                     for field in pfields {
173                         let name = field.node.name;
174                         let efield = efields.iter()
175                                             .find(|f| f.name.node == name)
176                                             .map(|f| &*f.expr);
177                         check_pat(cx, &field.node.pat, &efield, span, bindings);
178                     }
179                 } else {
180                     for field in pfields {
181                         check_pat(cx, &field.node.pat, init, span, bindings);
182                     }
183                 }
184             } else {
185                 for field in pfields {
186                     check_pat(cx, &field.node.pat, &None, span, bindings);
187                 }
188             }
189         }
190         PatKind::Tuple(ref inner, _) => {
191             if let Some(init_tup) = *init {
192                 if let ExprTup(ref tup) = init_tup.node {
193                     for (i, p) in inner.iter().enumerate() {
194                         check_pat(cx, p, &Some(&tup[i]), p.span, bindings);
195                     }
196                 } else {
197                     for p in inner {
198                         check_pat(cx, p, init, span, bindings);
199                     }
200                 }
201             } else {
202                 for p in inner {
203                     check_pat(cx, p, &None, span, bindings);
204                 }
205             }
206         }
207         PatKind::Box(ref inner) => {
208             if let Some(initp) = *init {
209                 if let ExprBox(ref inner_init) = initp.node {
210                     check_pat(cx, inner, &Some(&**inner_init), span, bindings);
211                 } else {
212                     check_pat(cx, inner, init, span, bindings);
213                 }
214             } else {
215                 check_pat(cx, inner, init, span, bindings);
216             }
217         }
218         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
219         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
220         _ => (),
221     }
222 }
223
224 fn lint_shadow<T>(cx: &LateContext, name: Name, span: Span, pattern_span: Span, init: &Option<T>, prev_span: Span)
225     where T: Deref<Target = Expr>
226 {
227     if let Some(ref expr) = *init {
228         if is_self_shadow(name, expr) {
229             span_lint_and_then(cx,
230                                SHADOW_SAME,
231                                span,
232                                &format!("`{}` is shadowed by itself in `{}`",
233                                         snippet(cx, pattern_span, "_"),
234                                         snippet(cx, expr.span, "..")),
235                                |db| { db.span_note(prev_span, "previous binding is here"); },
236             );
237         } else if contains_self(name, expr) {
238             span_lint_and_then(cx,
239                                SHADOW_REUSE,
240                                pattern_span,
241                                &format!("`{}` is shadowed by `{}` which reuses the original value",
242                                         snippet(cx, pattern_span, "_"),
243                                         snippet(cx, expr.span, "..")),
244                                |db| {
245                                    db.span_note(expr.span, "initialization happens here");
246                                    db.span_note(prev_span, "previous binding is here");
247                                });
248         } else {
249             span_lint_and_then(cx,
250                                SHADOW_UNRELATED,
251                                pattern_span,
252                                &format!("`{}` is shadowed by `{}`",
253                                         snippet(cx, pattern_span, "_"),
254                                         snippet(cx, expr.span, "..")),
255                                |db| {
256                                    db.span_note(expr.span, "initialization happens here");
257                                    db.span_note(prev_span, "previous binding is here");
258                                });
259         }
260
261     } else {
262         span_lint_and_then(cx,
263                            SHADOW_UNRELATED,
264                            span,
265                            &format!("{} shadows a previous declaration", snippet(cx, pattern_span, "_")),
266                            |db| { db.span_note(prev_span, "previous binding is here"); });
267     }
268 }
269
270 fn check_expr(cx: &LateContext, expr: &Expr, bindings: &mut Vec<(Name, Span)>) {
271     if in_external_macro(cx, expr.span) {
272         return;
273     }
274     match expr.node {
275         ExprUnary(_, ref e) |
276         ExprField(ref e, _) |
277         ExprTupField(ref e, _) |
278         ExprAddrOf(_, ref e) |
279         ExprBox(ref e) => check_expr(cx, e, bindings),
280         ExprBlock(ref block) |
281         ExprLoop(ref block, _) => check_block(cx, block, bindings),
282         // ExprCall
283         // ExprMethodCall
284         ExprVec(ref v) | ExprTup(ref v) => {
285             for e in v {
286                 check_expr(cx, e, bindings)
287             }
288         }
289         ExprIf(ref cond, ref then, ref otherwise) => {
290             check_expr(cx, cond, bindings);
291             check_block(cx, then, bindings);
292             if let Some(ref o) = *otherwise {
293                 check_expr(cx, o, bindings);
294             }
295         }
296         ExprWhile(ref cond, ref block, _) => {
297             check_expr(cx, cond, bindings);
298             check_block(cx, block, bindings);
299         }
300         ExprMatch(ref init, ref arms, _) => {
301             check_expr(cx, init, bindings);
302             let len = bindings.len();
303             for arm in arms {
304                 for pat in &arm.pats {
305                     check_pat(cx, pat, &Some(&**init), pat.span, bindings);
306                     // This is ugly, but needed to get the right type
307                     if let Some(ref guard) = arm.guard {
308                         check_expr(cx, guard, bindings);
309                     }
310                     check_expr(cx, &arm.body, bindings);
311                     bindings.truncate(len);
312                 }
313             }
314         }
315         _ => (),
316     }
317 }
318
319 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
320     match ty.node {
321         TyObjectSum(ref sty, _) |
322         TyVec(ref sty) => check_ty(cx, sty, bindings),
323         TyFixedLengthVec(ref fty, ref expr) => {
324             check_ty(cx, fty, bindings);
325             check_expr(cx, expr, bindings);
326         }
327         TyPtr(MutTy { ty: ref mty, .. }) |
328         TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
329         TyTup(ref tup) => {
330             for t in tup {
331                 check_ty(cx, t, bindings)
332             }
333         }
334         TyTypeof(ref expr) => check_expr(cx, expr, bindings),
335         _ => (),
336     }
337 }
338
339 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
340     match expr.node {
341         ExprBox(ref inner) |
342         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
343         ExprBlock(ref block) => {
344             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
345         }
346         ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
347         ExprPath(_, ref path) => path_eq_name(name, path),
348         _ => false,
349     }
350 }
351
352 fn path_eq_name(name: Name, path: &Path) -> bool {
353     !path.global && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
354 }
355
356 struct ContainsSelf {
357     name: Name,
358     result: bool,
359 }
360
361 impl<'v> Visitor<'v> for ContainsSelf {
362     fn visit_name(&mut self, _: Span, name: Name) {
363         if self.name == name {
364             self.result = true;
365         }
366     }
367 }
368
369 fn contains_self(name: Name, expr: &Expr) -> bool {
370     let mut cs = ContainsSelf {
371         name: name,
372         result: false,
373     };
374     cs.visit_expr(expr);
375     cs.result
376 }