1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::reexport::*;
11 use crate::rustc::hir::intravisit::FnKind;
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::syntax::source_map::Span;
17 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
19 /// **What it does:** Checks for bindings that shadow other bindings already in
20 /// scope, while just changing reference level or mutability.
22 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
23 /// code. Still, some may opt to avoid it in their code base, they can set this
26 /// **Known problems:** This lint, as the other shadowing related lints,
27 /// currently only catches very simple patterns.
33 declare_clippy_lint! {
36 "rebinding a name to itself, e.g. `let mut x = &mut x`"
39 /// **What it does:** Checks for bindings that shadow other bindings already in
40 /// scope, while reusing the original value.
42 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
43 /// code. Still, some argue that name shadowing like this hurts readability,
44 /// because a value may be bound to different things depending on position in
47 /// **Known problems:** This lint, as the other shadowing related lints,
48 /// currently only catches very simple patterns.
54 /// use different variable name:
58 declare_clippy_lint! {
61 "rebinding a name to an expression that re-uses the original value, e.g. \
65 /// **What it does:** Checks for bindings that shadow other bindings already in
66 /// scope, either without a initialization or with one that does not even use
67 /// the original value.
69 /// **Why is this bad?** Name shadowing can hurt readability, especially in
70 /// large code bases, because it is easy to lose track of the active binding at
71 /// any place in the code. This can be alleviated by either giving more specific
72 /// names to bindings or introducing more scopes to contain the bindings.
74 /// **Known problems:** This lint, as the other shadowing related lints,
75 /// currently only catches very simple patterns.
80 /// let x = z; // shadows the earlier binding
82 declare_clippy_lint! {
85 "rebinding a name without even using the original value"
88 #[derive(Copy, Clone)]
91 impl LintPass for Pass {
92 fn get_lints(&self) -> LintArray {
93 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
97 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
100 cx: &LateContext<'a, 'tcx>,
107 if in_external_macro(cx.sess(), body.value.span) {
110 check_fn(cx, decl, body);
114 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
115 let mut bindings = Vec::new();
116 for arg in iter_input_pats(decl, body) {
117 if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
118 bindings.push((ident.name, ident.span))
121 check_expr(cx, &body.value, &mut bindings);
124 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
125 let len = bindings.len();
126 for stmt in &block.stmts {
128 StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
129 StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
132 if let Some(ref o) = block.expr {
133 check_expr(cx, o, bindings);
135 bindings.truncate(len);
138 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
139 if in_external_macro(cx.sess(), decl.span) {
142 if higher::is_from_for_desugar(decl) {
145 if let DeclKind::Local(ref local) = decl.node {
153 if let Some(ref t) = *ty {
154 check_ty(cx, t, bindings)
156 if let Some(ref o) = *init {
157 check_expr(cx, o, bindings);
158 check_pat(cx, pat, Some(o), span, bindings);
160 check_pat(cx, pat, None, span, bindings);
165 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
166 let var_ty = cx.tables.node_id_to_type(pat_id);
168 ty::Adt(..) => false,
173 fn check_pat<'a, 'tcx>(
174 cx: &LateContext<'a, 'tcx>,
176 init: Option<&'tcx Expr>,
178 bindings: &mut Vec<(Name, Span)>,
180 // TODO: match more stuff / destructuring
182 PatKind::Binding(_, _, ident, ref inner) => {
183 let name = ident.name;
184 if is_binding(cx, pat.hir_id) {
185 let mut new_binding = true;
186 for tup in bindings.iter_mut() {
188 lint_shadow(cx, name, span, pat.span, init, tup.1);
195 bindings.push((name, ident.span));
198 if let Some(ref p) = *inner {
199 check_pat(cx, p, init, span, bindings);
202 PatKind::Struct(_, ref pfields, _) => {
203 if let Some(init_struct) = init {
204 if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
205 for field in pfields {
206 let name = field.node.ident.name;
207 let efield = efields.iter().find(|f| f.ident.name == name).map(|f| &*f.expr);
208 check_pat(cx, &field.node.pat, efield, span, bindings);
211 for field in pfields {
212 check_pat(cx, &field.node.pat, init, span, bindings);
216 for field in pfields {
217 check_pat(cx, &field.node.pat, None, span, bindings);
221 PatKind::Tuple(ref inner, _) => {
222 if let Some(init_tup) = init {
223 if let ExprKind::Tup(ref tup) = init_tup.node {
224 for (i, p) in inner.iter().enumerate() {
225 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
229 check_pat(cx, p, init, span, bindings);
234 check_pat(cx, p, None, span, bindings);
238 PatKind::Box(ref inner) => {
239 if let Some(initp) = init {
240 if let ExprKind::Box(ref inner_init) = initp.node {
241 check_pat(cx, inner, Some(&**inner_init), span, bindings);
243 check_pat(cx, inner, init, span, bindings);
246 check_pat(cx, inner, init, span, bindings);
249 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
250 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
255 fn lint_shadow<'a, 'tcx: 'a>(
256 cx: &LateContext<'a, 'tcx>,
260 init: Option<&'tcx Expr>,
263 if let Some(expr) = init {
264 if is_self_shadow(name, expr) {
270 "`{}` is shadowed by itself in `{}`",
271 snippet(cx, pattern_span, "_"),
272 snippet(cx, expr.span, "..")
275 db.span_note(prev_span, "previous binding is here");
278 } else if contains_name(name, expr) {
284 "`{}` is shadowed by `{}` which reuses the original value",
285 snippet(cx, pattern_span, "_"),
286 snippet(cx, expr.span, "..")
289 db.span_note(expr.span, "initialization happens here");
290 db.span_note(prev_span, "previous binding is here");
299 "`{}` is shadowed by `{}`",
300 snippet(cx, pattern_span, "_"),
301 snippet(cx, expr.span, "..")
304 db.span_note(expr.span, "initialization happens here");
305 db.span_note(prev_span, "previous binding is here");
314 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
316 db.span_note(prev_span, "previous binding is here");
322 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
323 if in_external_macro(cx.sess(), expr.span) {
327 ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
328 check_expr(cx, e, bindings)
330 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
332 // ExprKind::MethodCall
333 ExprKind::Array(ref v) | ExprKind::Tup(ref v) => {
335 check_expr(cx, e, bindings)
338 ExprKind::If(ref cond, ref then, ref otherwise) => {
339 check_expr(cx, cond, bindings);
340 check_expr(cx, &**then, bindings);
341 if let Some(ref o) = *otherwise {
342 check_expr(cx, o, bindings);
345 ExprKind::While(ref cond, ref block, _) => {
346 check_expr(cx, cond, bindings);
347 check_block(cx, block, bindings);
349 ExprKind::Match(ref init, ref arms, _) => {
350 check_expr(cx, init, bindings);
351 let len = bindings.len();
353 for pat in &arm.pats {
354 check_pat(cx, pat, Some(&**init), pat.span, bindings);
355 // This is ugly, but needed to get the right type
356 if let Some(ref guard) = arm.guard {
358 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
361 check_expr(cx, &arm.body, bindings);
362 bindings.truncate(len);
370 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
372 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
373 TyKind::Array(ref fty, ref anon_const) => {
374 check_ty(cx, fty, bindings);
375 check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings);
377 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
378 check_ty(cx, mty, bindings)
380 TyKind::Tup(ref tup) => {
382 check_ty(cx, t, bindings)
385 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings),
390 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
392 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
393 ExprKind::Block(ref block, _) => {
394 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
396 ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
397 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
402 fn path_eq_name(name: Name, path: &Path) -> bool {
403 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()