1 use crate::reexport::*;
2 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
3 use rustc::hir::intravisit::FnKind;
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use syntax::source_map::Span;
10 declare_clippy_lint! {
11 /// **What it does:** Checks for bindings that shadow other bindings already in
12 /// scope, while just changing reference level or mutability.
14 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
15 /// code. Still, some may opt to avoid it in their code base, they can set this
18 /// **Known problems:** This lint, as the other shadowing related lints,
19 /// currently only catches very simple patterns.
27 "rebinding a name to itself, e.g., `let mut x = &mut x`"
30 declare_clippy_lint! {
31 /// **What it does:** Checks for bindings that shadow other bindings already in
32 /// scope, while reusing the original value.
34 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
35 /// code. Still, some argue that name shadowing like this hurts readability,
36 /// because a value may be bound to different things depending on position in
39 /// **Known problems:** This lint, as the other shadowing related lints,
40 /// currently only catches very simple patterns.
46 /// use different variable name:
52 "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
55 declare_clippy_lint! {
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.
71 /// let x = z; // shadows the earlier binding
75 "rebinding a name without even using the original value"
78 declare_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
80 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Shadow {
83 cx: &LateContext<'a, 'tcx>,
90 if in_external_macro(cx.sess(), body.value.span) {
93 check_fn(cx, decl, body);
97 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
98 let mut bindings = Vec::new();
99 for arg in iter_input_pats(decl, body) {
100 if let PatKind::Binding(.., ident, _) = arg.pat.node {
101 bindings.push((ident.name, ident.span))
104 check_expr(cx, &body.value, &mut bindings);
107 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
108 let len = bindings.len();
109 for stmt in &block.stmts {
111 StmtKind::Local(ref local) => check_local(cx, local, bindings),
112 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => check_expr(cx, e, bindings),
113 StmtKind::Item(..) => {},
116 if let Some(ref o) = block.expr {
117 check_expr(cx, o, bindings);
119 bindings.truncate(len);
122 fn check_local<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, local: &'tcx Local, bindings: &mut Vec<(Name, Span)>) {
123 if in_external_macro(cx.sess(), local.span) {
126 if higher::is_from_for_desugar(local) {
136 if let Some(ref t) = *ty {
137 check_ty(cx, t, bindings)
139 if let Some(ref o) = *init {
140 check_expr(cx, o, bindings);
141 check_pat(cx, pat, Some(o), span, bindings);
143 check_pat(cx, pat, None, span, bindings);
147 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
148 let var_ty = cx.tables.node_type(pat_id);
150 ty::Adt(..) => false,
155 fn check_pat<'a, 'tcx>(
156 cx: &LateContext<'a, 'tcx>,
158 init: Option<&'tcx Expr>,
160 bindings: &mut Vec<(Name, Span)>,
162 // TODO: match more stuff / destructuring
164 PatKind::Binding(.., ident, ref inner) => {
165 let name = ident.name;
166 if is_binding(cx, pat.hir_id) {
167 let mut new_binding = true;
168 for tup in bindings.iter_mut() {
170 lint_shadow(cx, name, span, pat.span, init, tup.1);
177 bindings.push((name, ident.span));
180 if let Some(ref p) = *inner {
181 check_pat(cx, p, init, span, bindings);
184 PatKind::Struct(_, ref pfields, _) => {
185 if let Some(init_struct) = init {
186 if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
187 for field in pfields {
188 let name = field.node.ident.name;
191 .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
192 check_pat(cx, &field.node.pat, efield, span, bindings);
195 for field in pfields {
196 check_pat(cx, &field.node.pat, init, span, bindings);
200 for field in pfields {
201 check_pat(cx, &field.node.pat, None, span, bindings);
205 PatKind::Tuple(ref inner, _) => {
206 if let Some(init_tup) = init {
207 if let ExprKind::Tup(ref tup) = init_tup.node {
208 for (i, p) in inner.iter().enumerate() {
209 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
213 check_pat(cx, p, init, span, bindings);
218 check_pat(cx, p, None, span, bindings);
222 PatKind::Box(ref inner) => {
223 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);
233 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
234 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
239 fn lint_shadow<'a, 'tcx: 'a>(
240 cx: &LateContext<'a, 'tcx>,
244 init: Option<&'tcx Expr>,
247 if let Some(expr) = init {
248 if is_self_shadow(name, expr) {
254 "`{}` is shadowed by itself in `{}`",
255 snippet(cx, pattern_span, "_"),
256 snippet(cx, expr.span, "..")
259 db.span_note(prev_span, "previous binding is here");
262 } else if contains_name(name, expr) {
268 "`{}` is shadowed by `{}` which reuses the original value",
269 snippet(cx, pattern_span, "_"),
270 snippet(cx, expr.span, "..")
273 db.span_note(expr.span, "initialization happens here");
274 db.span_note(prev_span, "previous binding is here");
283 "`{}` is shadowed by `{}`",
284 snippet(cx, pattern_span, "_"),
285 snippet(cx, expr.span, "..")
288 db.span_note(expr.span, "initialization happens here");
289 db.span_note(prev_span, "previous binding is here");
298 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
300 db.span_note(prev_span, "previous binding is here");
306 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
307 if in_external_macro(cx.sess(), expr.span) {
311 ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
312 check_expr(cx, e, bindings)
314 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
316 // ExprKind::MethodCall
317 ExprKind::Array(ref v) | ExprKind::Tup(ref v) => {
319 check_expr(cx, e, bindings)
322 ExprKind::While(ref cond, ref block, _) => {
323 check_expr(cx, cond, bindings);
324 check_block(cx, block, bindings);
326 ExprKind::Match(ref init, ref arms, _) => {
327 check_expr(cx, init, bindings);
328 let len = bindings.len();
330 for pat in &arm.pats {
331 check_pat(cx, pat, Some(&**init), pat.span, bindings);
332 // This is ugly, but needed to get the right type
333 if let Some(ref guard) = arm.guard {
335 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
338 check_expr(cx, &arm.body, bindings);
339 bindings.truncate(len);
347 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
349 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
350 TyKind::Array(ref fty, ref anon_const) => {
351 check_ty(cx, fty, bindings);
352 check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
354 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
355 check_ty(cx, mty, bindings)
357 TyKind::Tup(ref tup) => {
359 check_ty(cx, t, bindings)
362 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
367 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
369 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
370 ExprKind::Block(ref block, _) => {
371 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
373 ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
374 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
379 fn path_eq_name(name: Name, path: &Path) -> bool {
380 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()