1 use crate::reexport::*;
3 use rustc::{declare_lint, lint_array};
5 use rustc::hir::intravisit::FnKind;
7 use syntax::codemap::Span;
8 use crate::utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then};
10 /// **What it does:** Checks for bindings that shadow other bindings already in
11 /// scope, while just changing reference level or mutability.
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
17 /// **Known problems:** This lint, as the other shadowing related lints,
18 /// currently only catches very simple patterns.
24 declare_clippy_lint! {
27 "rebinding a name to itself, e.g. `let mut x = &mut x`"
30 /// **What it does:** Checks for bindings that shadow other bindings already in
31 /// scope, while reusing the original value.
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
38 /// **Known problems:** This lint, as the other shadowing related lints,
39 /// currently only catches very simple patterns.
45 declare_clippy_lint! {
48 "rebinding a name to an expression that re-uses the original value, e.g. \
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.
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.
61 /// **Known problems:** This lint, as the other shadowing related lints,
62 /// currently only catches very simple patterns.
66 /// let x = y; let x = z; // shadows the earlier binding
68 declare_clippy_lint! {
71 "rebinding a name without even using the original value"
74 #[derive(Copy, Clone)]
77 impl LintPass for Pass {
78 fn get_lints(&self) -> LintArray {
79 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
83 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
86 cx: &LateContext<'a, 'tcx>,
93 if in_external_macro(cx, body.value.span) {
96 check_fn(cx, decl, body);
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))
107 check_expr(cx, &body.value, &mut bindings);
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 {
114 StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
115 StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
118 if let Some(ref o) = block.expr {
119 check_expr(cx, o, bindings);
121 bindings.truncate(len);
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) {
128 if higher::is_from_for_desugar(decl) {
131 if let DeclKind::Local(ref local) = decl.node {
139 if let Some(ref t) = *ty {
140 check_ty(cx, t, bindings)
142 if let Some(ref o) = *init {
143 check_expr(cx, o, bindings);
144 check_pat(cx, pat, Some(o), span, bindings);
146 check_pat(cx, pat, None, span, bindings);
151 fn is_binding(cx: &LateContext, pat_id: HirId) -> bool {
152 let var_ty = cx.tables.node_id_to_type(pat_id);
154 ty::TyAdt(..) => false,
159 fn check_pat<'a, 'tcx>(
160 cx: &LateContext<'a, 'tcx>,
162 init: Option<&'tcx Expr>,
164 bindings: &mut Vec<(Name, Span)>,
166 // TODO: match more stuff / destructuring
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() {
174 lint_shadow(cx, name, span, pat.span, init, tup.1);
181 bindings.push((name, ident.span));
184 if let Some(ref p) = *inner {
185 check_pat(cx, p, init, span, bindings);
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;
194 .find(|f| f.ident.name == name)
196 check_pat(cx, &field.node.pat, efield, span, bindings);
199 for field in pfields {
200 check_pat(cx, &field.node.pat, init, span, bindings);
204 for field in pfields {
205 check_pat(cx, &field.node.pat, None, span, bindings);
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);
215 check_pat(cx, p, init, span, bindings);
220 check_pat(cx, p, None, span, bindings);
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);
227 check_pat(cx, inner, init, span, bindings);
230 check_pat(cx, inner, init, span, bindings);
232 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
233 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
238 fn lint_shadow<'a, 'tcx: 'a>(
239 cx: &LateContext<'a, 'tcx>,
243 init: Option<&'tcx Expr>,
246 if let Some(expr) = init {
247 if is_self_shadow(name, expr) {
253 "`{}` is shadowed by itself in `{}`",
254 snippet(cx, pattern_span, "_"),
255 snippet(cx, expr.span, "..")
258 db.span_note(prev_span, "previous binding is here");
261 } else if contains_name(name, expr) {
267 "`{}` is shadowed by `{}` which reuses the original value",
268 snippet(cx, pattern_span, "_"),
269 snippet(cx, expr.span, "..")
272 db.span_note(expr.span, "initialization happens here");
273 db.span_note(prev_span, "previous binding is here");
282 "`{}` is shadowed by `{}`",
283 snippet(cx, pattern_span, "_"),
284 snippet(cx, expr.span, "..")
287 db.span_note(expr.span, "initialization happens here");
288 db.span_note(prev_span, "previous binding is here");
297 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
299 db.span_note(prev_span, "previous binding is here");
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) {
310 ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
311 check_expr(cx, e, bindings)
313 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
315 // ExprKind::MethodCall
316 ExprKind::Array(ref v) | ExprKind::Tup(ref v) => for e in v {
317 check_expr(cx, e, bindings)
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);
326 ExprKind::While(ref cond, ref block, _) => {
327 check_expr(cx, cond, bindings);
328 check_block(cx, block, bindings);
330 ExprKind::Match(ref init, ref arms, _) => {
331 check_expr(cx, init, bindings);
332 let len = bindings.len();
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);
340 check_expr(cx, &arm.body, bindings);
341 bindings.truncate(len);
349 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
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);
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)
360 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings),
365 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
367 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
368 ExprKind::Block(ref block, _) => {
369 block.stmts.is_empty()
373 .map_or(false, |e| is_self_shadow(name, e))
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),
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()