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