]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/shadow.rs
Add empty_enum lint (just a copy of large_enum_variant for now)
[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| {
254                 db.span_note(prev_span, "previous binding is here");
255             });
256         } else if contains_self(cx, name, expr) {
257             span_lint_and_then(cx,
258                                SHADOW_REUSE,
259                                pattern_span,
260                                &format!("`{}` is shadowed by `{}` which reuses the original value",
261                                         snippet(cx, pattern_span, "_"),
262                                         snippet(cx, expr.span, "..")),
263                                |db| {
264                 db.span_note(expr.span, "initialization happens here");
265                 db.span_note(prev_span, "previous binding is here");
266             });
267         } else {
268             span_lint_and_then(cx,
269                                SHADOW_UNRELATED,
270                                pattern_span,
271                                &format!("`{}` is shadowed by `{}`",
272                                         snippet(cx, pattern_span, "_"),
273                                         snippet(cx, expr.span, "..")),
274                                |db| {
275                 db.span_note(expr.span, "initialization happens here");
276                 db.span_note(prev_span, "previous binding is here");
277             });
278         }
279
280     } else {
281         span_lint_and_then(cx,
282                            SHADOW_UNRELATED,
283                            span,
284                            &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
285                            |db| {
286             db.span_note(prev_span, "previous binding is here");
287         });
288     }
289 }
290
291 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
292     if in_external_macro(cx, expr.span) {
293         return;
294     }
295     match expr.node {
296         ExprUnary(_, ref e) |
297         ExprField(ref e, _) |
298         ExprTupField(ref e, _) |
299         ExprAddrOf(_, ref e) |
300         ExprBox(ref e) => check_expr(cx, e, bindings),
301         ExprBlock(ref block) |
302         ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
303         // ExprCall
304         // ExprMethodCall
305         ExprArray(ref v) | ExprTup(ref v) => {
306             for e in v {
307                 check_expr(cx, e, bindings)
308             }
309         },
310         ExprIf(ref cond, ref then, ref otherwise) => {
311             check_expr(cx, cond, bindings);
312             check_block(cx, then, bindings);
313             if let Some(ref o) = *otherwise {
314                 check_expr(cx, o, bindings);
315             }
316         },
317         ExprWhile(ref cond, ref block, _) => {
318             check_expr(cx, cond, bindings);
319             check_block(cx, block, bindings);
320         },
321         ExprMatch(ref init, ref arms, _) => {
322             check_expr(cx, init, bindings);
323             let len = bindings.len();
324             for arm in arms {
325                 for pat in &arm.pats {
326                     check_pat(cx, pat, Some(&**init), pat.span, bindings);
327                     // This is ugly, but needed to get the right type
328                     if let Some(ref guard) = arm.guard {
329                         check_expr(cx, guard, bindings);
330                     }
331                     check_expr(cx, &arm.body, bindings);
332                     bindings.truncate(len);
333                 }
334             }
335         },
336         _ => (),
337     }
338 }
339
340 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
341     match ty.node {
342         TySlice(ref sty) => check_ty(cx, sty, bindings),
343         TyArray(ref fty, body_id) => {
344             check_ty(cx, fty, bindings);
345             check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings);
346         },
347         TyPtr(MutTy { ty: ref mty, .. }) |
348         TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
349         TyTup(ref tup) => {
350             for t in tup {
351                 check_ty(cx, t, bindings)
352             }
353         },
354         TyTypeof(body_id) => check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings),
355         _ => (),
356     }
357 }
358
359 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
360     match expr.node {
361         ExprBox(ref inner) |
362         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
363         ExprBlock(ref block) => {
364             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
365         },
366         ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
367         ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
368         _ => false,
369     }
370 }
371
372 fn path_eq_name(name: Name, path: &Path) -> bool {
373     !path.is_global() && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
374 }
375
376 struct ContainsSelf<'a, 'tcx: 'a> {
377     name: Name,
378     result: bool,
379     cx: &'a LateContext<'a, 'tcx>,
380 }
381
382 impl<'a, 'tcx: 'a> Visitor<'tcx> for ContainsSelf<'a, 'tcx> {
383     fn visit_name(&mut self, _: Span, name: Name) {
384         if self.name == name {
385             self.result = true;
386         }
387     }
388     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
389         NestedVisitorMap::All(&self.cx.tcx.hir)
390     }
391 }
392
393 fn contains_self<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, name: Name, expr: &'tcx Expr) -> bool {
394     let mut cs = ContainsSelf {
395         name: name,
396         result: false,
397         cx: cx,
398     };
399     cs.visit_expr(expr);
400     cs.result
401 }