1 use crate::reexport::*;
3 use rustc::{declare_lint, lint_array};
5 use rustc::hir::intravisit::FnKind;
7 use syntax::source_map::Span;
8 use crate::utils::{contains_name, higher, 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 /// use different variable name:
49 declare_clippy_lint! {
52 "rebinding a name to an expression that re-uses the original value, e.g. \
56 /// **What it does:** Checks for bindings that shadow other bindings already in
57 /// scope, either without a initialization or with one that does not even use
58 /// the original value.
60 /// **Why is this bad?** Name shadowing can hurt readability, especially in
61 /// large code bases, because it is easy to lose track of the active binding at
62 /// any place in the code. This can be alleviated by either giving more specific
63 /// names to bindings or introducing more scopes to contain the bindings.
65 /// **Known problems:** This lint, as the other shadowing related lints,
66 /// currently only catches very simple patterns.
70 /// let x = y; let x = z; // shadows the earlier binding
72 declare_clippy_lint! {
75 "rebinding a name without even using the original value"
78 #[derive(Copy, Clone)]
81 impl LintPass for Pass {
82 fn get_lints(&self) -> LintArray {
83 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
87 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
90 cx: &LateContext<'a, 'tcx>,
97 if in_external_macro(cx.sess(), body.value.span) {
100 check_fn(cx, decl, body);
104 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
105 let mut bindings = Vec::new();
106 for arg in iter_input_pats(decl, body) {
107 if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
108 bindings.push((ident.name, ident.span))
111 check_expr(cx, &body.value, &mut bindings);
114 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
115 let len = bindings.len();
116 for stmt in &block.stmts {
118 StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
119 StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
122 if let Some(ref o) = block.expr {
123 check_expr(cx, o, bindings);
125 bindings.truncate(len);
128 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
129 if in_external_macro(cx.sess(), decl.span) {
132 if higher::is_from_for_desugar(decl) {
135 if let DeclKind::Local(ref local) = decl.node {
143 if let Some(ref t) = *ty {
144 check_ty(cx, t, bindings)
146 if let Some(ref o) = *init {
147 check_expr(cx, o, bindings);
148 check_pat(cx, pat, Some(o), span, bindings);
150 check_pat(cx, pat, None, span, bindings);
155 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
156 let var_ty = cx.tables.node_id_to_type(pat_id);
158 ty::Adt(..) => false,
163 fn check_pat<'a, 'tcx>(
164 cx: &LateContext<'a, 'tcx>,
166 init: Option<&'tcx Expr>,
168 bindings: &mut Vec<(Name, Span)>,
170 // TODO: match more stuff / destructuring
172 PatKind::Binding(_, _, ident, ref inner) => {
173 let name = ident.name;
174 if is_binding(cx, pat.hir_id) {
175 let mut new_binding = true;
176 for tup in bindings.iter_mut() {
178 lint_shadow(cx, name, span, pat.span, init, tup.1);
185 bindings.push((name, ident.span));
188 if let Some(ref p) = *inner {
189 check_pat(cx, p, init, span, bindings);
192 PatKind::Struct(_, ref pfields, _) => if let Some(init_struct) = init {
193 if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
194 for field in pfields {
195 let name = field.node.ident.name;
198 .find(|f| f.ident.name == name)
200 check_pat(cx, &field.node.pat, efield, span, bindings);
203 for field in pfields {
204 check_pat(cx, &field.node.pat, init, span, bindings);
208 for field in pfields {
209 check_pat(cx, &field.node.pat, None, span, bindings);
212 PatKind::Tuple(ref inner, _) => if let Some(init_tup) = init {
213 if let ExprKind::Tup(ref tup) = init_tup.node {
214 for (i, p) in inner.iter().enumerate() {
215 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
219 check_pat(cx, p, init, span, bindings);
224 check_pat(cx, p, None, span, bindings);
227 PatKind::Box(ref inner) => if let Some(initp) = init {
228 if let ExprKind::Box(ref inner_init) = initp.node {
229 check_pat(cx, inner, Some(&**inner_init), span, bindings);
231 check_pat(cx, inner, init, span, bindings);
234 check_pat(cx, inner, init, span, bindings);
236 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
237 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
242 fn lint_shadow<'a, 'tcx: 'a>(
243 cx: &LateContext<'a, 'tcx>,
247 init: Option<&'tcx Expr>,
250 if let Some(expr) = init {
251 if is_self_shadow(name, expr) {
257 "`{}` is shadowed by itself in `{}`",
258 snippet(cx, pattern_span, "_"),
259 snippet(cx, expr.span, "..")
262 db.span_note(prev_span, "previous binding is here");
265 } else if contains_name(name, expr) {
271 "`{}` is shadowed by `{}` which reuses the original value",
272 snippet(cx, pattern_span, "_"),
273 snippet(cx, expr.span, "..")
276 db.span_note(expr.span, "initialization happens here");
277 db.span_note(prev_span, "previous binding is here");
286 "`{}` is shadowed by `{}`",
287 snippet(cx, pattern_span, "_"),
288 snippet(cx, expr.span, "..")
291 db.span_note(expr.span, "initialization happens here");
292 db.span_note(prev_span, "previous binding is here");
301 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
303 db.span_note(prev_span, "previous binding is here");
309 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
310 if in_external_macro(cx.sess(), expr.span) {
314 ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
315 check_expr(cx, e, bindings)
317 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
319 // ExprKind::MethodCall
320 ExprKind::Array(ref v) | ExprKind::Tup(ref v) => for e in v {
321 check_expr(cx, e, bindings)
323 ExprKind::If(ref cond, ref then, ref otherwise) => {
324 check_expr(cx, cond, bindings);
325 check_expr(cx, &**then, bindings);
326 if let Some(ref o) = *otherwise {
327 check_expr(cx, o, bindings);
330 ExprKind::While(ref cond, ref block, _) => {
331 check_expr(cx, cond, bindings);
332 check_block(cx, block, bindings);
334 ExprKind::Match(ref init, ref arms, _) => {
335 check_expr(cx, init, bindings);
336 let len = bindings.len();
338 for pat in &arm.pats {
339 check_pat(cx, pat, Some(&**init), pat.span, bindings);
340 // This is ugly, but needed to get the right type
341 if let Some(ref guard) = arm.guard {
342 check_expr(cx, guard, bindings);
344 check_expr(cx, &arm.body, bindings);
345 bindings.truncate(len);
353 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
355 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
356 TyKind::Array(ref fty, ref anon_const) => {
357 check_ty(cx, fty, bindings);
358 check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings);
360 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
361 TyKind::Tup(ref tup) => for t in tup {
362 check_ty(cx, t, bindings)
364 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir.body(anon_const.body).value, bindings),
369 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
371 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
372 ExprKind::Block(ref block, _) => {
373 block.stmts.is_empty()
377 .map_or(false, |e| is_self_shadow(name, e))
379 ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
380 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
385 fn path_eq_name(name: Name, path: &Path) -> bool {
386 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()