]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
f84e639d78d72bf8dd85e663d626c642e4b32fc5
[rust.git] / clippy_lints / src / shadow.rs
1 use reexport::*;
2 use rustc::lint::*;
3 use rustc::hir::*;
4 use rustc::hir::intravisit::{Visitor, FnKind, NestedVisitorMap};
5 use rustc::ty;
6 use syntax::codemap::Span;
7 use utils::{higher, in_external_macro, snippet, span_lint_and_then, iter_input_pats};
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, _) |
115             StmtSemi(ref e, _) => check_expr(cx, e, bindings),
116         }
117     }
118     if let Some(ref o) = block.expr {
119         check_expr(cx, o, bindings);
120     }
121     bindings.truncate(len);
122 }
123
124 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
125     if in_external_macro(cx, decl.span) {
126         return;
127     }
128     if higher::is_from_for_desugar(decl) {
129         return;
130     }
131     if let DeclLocal(ref local) = decl.node {
132         let Local { ref pat, ref ty, ref init, span, .. } = **local;
133         if let Some(ref t) = *ty {
134             check_ty(cx, t, bindings)
135         }
136         if let Some(ref o) = *init {
137             check_expr(cx, o, bindings);
138             check_pat(cx, pat, Some(o), span, bindings);
139         } else {
140             check_pat(cx, pat, None, span, bindings);
141         }
142     }
143 }
144
145 fn is_binding(cx: &LateContext, pat_id: NodeId) -> bool {
146     let var_ty = cx.tables.node_id_to_type(pat_id);
147     match var_ty.sty {
148         ty::TyAdt(..) => false,
149         _ => true,
150     }
151 }
152
153 fn check_pat<'a, 'tcx>(
154     cx: &LateContext<'a, 'tcx>,
155     pat: &'tcx Pat,
156     init: Option<&'tcx Expr>,
157     span: Span,
158     bindings: &mut Vec<(Name, Span)>
159 ) {
160     // TODO: match more stuff / destructuring
161     match pat.node {
162         PatKind::Binding(_, _, ref ident, ref inner) => {
163             let name = ident.node;
164             if is_binding(cx, pat.id) {
165                 let mut new_binding = true;
166                 for tup in bindings.iter_mut() {
167                     if tup.0 == name {
168                         lint_shadow(cx, name, span, pat.span, init, tup.1);
169                         tup.1 = ident.span;
170                         new_binding = false;
171                         break;
172                     }
173                 }
174                 if new_binding {
175                     bindings.push((name, ident.span));
176                 }
177             }
178             if let Some(ref p) = *inner {
179                 check_pat(cx, p, init, span, bindings);
180             }
181         },
182         PatKind::Struct(_, ref pfields, _) => {
183             if let Some(init_struct) = init {
184                 if let ExprStruct(_, ref efields, _) = init_struct.node {
185                     for field in pfields {
186                         let name = field.node.name;
187                         let efield = efields.iter()
188                             .find(|f| f.name.node == name)
189                             .map(|f| &*f.expr);
190                         check_pat(cx, &field.node.pat, efield, span, bindings);
191                     }
192                 } else {
193                     for field in pfields {
194                         check_pat(cx, &field.node.pat, init, span, bindings);
195                     }
196                 }
197             } else {
198                 for field in pfields {
199                     check_pat(cx, &field.node.pat, None, span, bindings);
200                 }
201             }
202         },
203         PatKind::Tuple(ref inner, _) => {
204             if let Some(init_tup) = init {
205                 if let ExprTup(ref tup) = init_tup.node {
206                     for (i, p) in inner.iter().enumerate() {
207                         check_pat(cx, p, Some(&tup[i]), p.span, bindings);
208                     }
209                 } else {
210                     for p in inner {
211                         check_pat(cx, p, init, span, bindings);
212                     }
213                 }
214             } else {
215                 for p in inner {
216                     check_pat(cx, p, None, span, bindings);
217                 }
218             }
219         },
220         PatKind::Box(ref inner) => {
221             if let Some(initp) = init {
222                 if let ExprBox(ref inner_init) = initp.node {
223                     check_pat(cx, inner, Some(&**inner_init), span, bindings);
224                 } else {
225                     check_pat(cx, inner, init, span, bindings);
226                 }
227             } else {
228                 check_pat(cx, inner, init, span, bindings);
229             }
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(cx,
248                                SHADOW_SAME,
249                                span,
250                                &format!("`{}` is shadowed by itself in `{}`",
251                                         snippet(cx, pattern_span, "_"),
252                                         snippet(cx, expr.span, "..")),
253                                |db| { db.span_note(prev_span, "previous binding is here"); });
254         } else if contains_self(cx, name, expr) {
255             span_lint_and_then(cx,
256                                SHADOW_REUSE,
257                                pattern_span,
258                                &format!("`{}` is shadowed by `{}` which reuses the original value",
259                                         snippet(cx, pattern_span, "_"),
260                                         snippet(cx, expr.span, "..")),
261                                |db| {
262                 db.span_note(expr.span, "initialization happens here");
263                 db.span_note(prev_span, "previous binding is here");
264             });
265         } else {
266             span_lint_and_then(cx,
267                                SHADOW_UNRELATED,
268                                pattern_span,
269                                &format!("`{}` is shadowed by `{}`",
270                                         snippet(cx, pattern_span, "_"),
271                                         snippet(cx, expr.span, "..")),
272                                |db| {
273                 db.span_note(expr.span, "initialization happens here");
274                 db.span_note(prev_span, "previous binding is here");
275             });
276         }
277
278     } else {
279         span_lint_and_then(cx,
280                            SHADOW_UNRELATED,
281                            span,
282                            &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
283                            |db| { db.span_note(prev_span, "previous binding is here"); });
284     }
285 }
286
287 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
288     if in_external_macro(cx, expr.span) {
289         return;
290     }
291     match expr.node {
292         ExprUnary(_, ref e) |
293         ExprField(ref e, _) |
294         ExprTupField(ref e, _) |
295         ExprAddrOf(_, ref e) |
296         ExprBox(ref e) => check_expr(cx, e, bindings),
297         ExprBlock(ref block) |
298         ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
299         // ExprCall
300         // ExprMethodCall
301         ExprArray(ref v) | ExprTup(ref v) => {
302             for e in v {
303                 check_expr(cx, e, bindings)
304             }
305         },
306         ExprIf(ref cond, ref then, ref otherwise) => {
307             check_expr(cx, cond, bindings);
308             check_block(cx, then, bindings);
309             if let Some(ref o) = *otherwise {
310                 check_expr(cx, o, bindings);
311             }
312         },
313         ExprWhile(ref cond, ref block, _) => {
314             check_expr(cx, cond, bindings);
315             check_block(cx, block, bindings);
316         },
317         ExprMatch(ref init, ref arms, _) => {
318             check_expr(cx, init, bindings);
319             let len = bindings.len();
320             for arm in arms {
321                 for pat in &arm.pats {
322                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
323                     // This is ugly, but needed to get the right type
324                     if let Some(ref guard) = arm.guard {
325                         check_expr(cx, guard, bindings);
326                     }
327                     check_expr(cx, &arm.body, bindings);
328                     bindings.truncate(len);
329                 }
330             }
331         },
332         _ => (),
333     }
334 }
335
336 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
337     match ty.node {
338         TyObjectSum(ref sty, _) |
339         TySlice(ref sty) => check_ty(cx, sty, bindings),
340         TyArray(ref fty, body_id) => {
341             check_ty(cx, fty, bindings);
342             check_expr(cx, &cx.tcx.map.body(body_id).value, bindings);
343         },
344         TyPtr(MutTy { ty: ref mty, .. }) |
345         TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
346         TyTup(ref tup) => {
347             for t in tup {
348                 check_ty(cx, t, bindings)
349             }
350         },
351         TyTypeof(body_id) => check_expr(cx, &cx.tcx.map.body(body_id).value, bindings),
352         _ => (),
353     }
354 }
355
356 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
357     match expr.node {
358         ExprBox(ref inner) |
359         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
360         ExprBlock(ref block) => {
361             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
362         },
363         ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
364         ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
365         _ => false,
366     }
367 }
368
369 fn path_eq_name(name: Name, path: &Path) -> bool {
370     !path.is_global() && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
371 }
372
373 struct ContainsSelf<'a, 'tcx: 'a> {
374     name: Name,
375     result: bool,
376     cx: &'a LateContext<'a, 'tcx>,
377 }
378
379 impl<'a, 'tcx: 'a> Visitor<'tcx> for ContainsSelf<'a, 'tcx> {
380     fn visit_name(&mut self, _: Span, name: Name) {
381         if self.name == name {
382             self.result = true;
383         }
384     }
385     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
386         NestedVisitorMap::All(&self.cx.tcx.map)
387     }
388 }
389
390 fn contains_self<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, name: Name, expr: &'tcx Expr) -> bool {
391     let mut cs = ContainsSelf {
392         name: name,
393         result: false,
394         cx: cx,
395     };
396     cs.visit_expr(expr);
397     cs.result
398 }