4 use rustc::hir::intravisit::FnKind;
6 use syntax::codemap::Span;
7 use utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then};
9 /// **What it does:** Checks for bindings that shadow other bindings already in
10 /// scope, while just changing reference level or mutability.
12 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
13 /// code. Still, some may opt to avoid it in their code base, they can set this
16 /// **Known problems:** This lint, as the other shadowing related lints,
17 /// currently only catches very simple patterns.
23 declare_clippy_lint! {
26 "rebinding a name to itself, e.g. `let mut x = &mut x`"
29 /// **What it does:** Checks for bindings that shadow other bindings already in
30 /// scope, while reusing the original value.
32 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
33 /// code. Still, some argue that name shadowing like this hurts readability,
34 /// because a value may be bound to different things depending on position in
37 /// **Known problems:** This lint, as the other shadowing related lints,
38 /// currently only catches very simple patterns.
44 declare_clippy_lint! {
47 "rebinding a name to an expression that re-uses the original value, e.g. \
51 /// **What it does:** Checks for bindings that shadow other bindings already in
52 /// scope, either without a initialization or with one that does not even use
53 /// the original value.
55 /// **Why is this bad?** Name shadowing can hurt readability, especially in
56 /// large code bases, because it is easy to lose track of the active binding at
57 /// any place in the code. This can be alleviated by either giving more specific
58 /// names to bindings or introducing more scopes to contain the bindings.
60 /// **Known problems:** This lint, as the other shadowing related lints,
61 /// currently only catches very simple patterns.
65 /// let x = y; let x = z; // shadows the earlier binding
67 declare_clippy_lint! {
70 "rebinding a name without even using the original value"
73 #[derive(Copy, Clone)]
76 impl LintPass for Pass {
77 fn get_lints(&self) -> LintArray {
78 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
82 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
85 cx: &LateContext<'a, 'tcx>,
92 if in_external_macro(cx, body.value.span) {
95 check_fn(cx, decl, body);
99 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
100 let mut bindings = Vec::new();
101 for arg in iter_input_pats(decl, body) {
102 if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
103 bindings.push((ident.node, ident.span))
106 check_expr(cx, &body.value, &mut bindings);
109 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
110 let len = bindings.len();
111 for stmt in &block.stmts {
113 StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
114 StmtExpr(ref e, _) | StmtSemi(ref e, _) => check_expr(cx, e, bindings),
117 if let Some(ref o) = block.expr {
118 check_expr(cx, o, bindings);
120 bindings.truncate(len);
123 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
124 if in_external_macro(cx, decl.span) {
127 if higher::is_from_for_desugar(decl) {
130 if let DeclLocal(ref local) = decl.node {
138 if let Some(ref t) = *ty {
139 check_ty(cx, t, bindings)
141 if let Some(ref o) = *init {
142 check_expr(cx, o, bindings);
143 check_pat(cx, pat, Some(o), span, bindings);
145 check_pat(cx, pat, None, span, bindings);
150 fn is_binding(cx: &LateContext, pat_id: HirId) -> bool {
151 let var_ty = cx.tables.node_id_to_type(pat_id);
153 ty::TyAdt(..) => false,
158 fn check_pat<'a, 'tcx>(
159 cx: &LateContext<'a, 'tcx>,
161 init: Option<&'tcx Expr>,
163 bindings: &mut Vec<(Name, Span)>,
165 // TODO: match more stuff / destructuring
167 PatKind::Binding(_, _, ref ident, ref inner) => {
168 let name = ident.node;
169 if is_binding(cx, pat.hir_id) {
170 let mut new_binding = true;
171 for tup in bindings.iter_mut() {
173 lint_shadow(cx, name, span, pat.span, init, tup.1);
180 bindings.push((name, ident.span));
183 if let Some(ref p) = *inner {
184 check_pat(cx, p, init, span, bindings);
187 PatKind::Struct(_, ref pfields, _) => if let Some(init_struct) = init {
188 if let ExprStruct(_, ref efields, _) = init_struct.node {
189 for field in pfields {
190 let name = field.node.name;
193 .find(|f| f.name.node == name)
195 check_pat(cx, &field.node.pat, efield, span, bindings);
198 for field in pfields {
199 check_pat(cx, &field.node.pat, init, span, bindings);
203 for field in pfields {
204 check_pat(cx, &field.node.pat, None, span, bindings);
207 PatKind::Tuple(ref inner, _) => if let Some(init_tup) = init {
208 if let ExprTup(ref tup) = init_tup.node {
209 for (i, p) in inner.iter().enumerate() {
210 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
214 check_pat(cx, p, init, span, bindings);
219 check_pat(cx, p, None, span, bindings);
222 PatKind::Box(ref inner) => if let Some(initp) = init {
223 if let ExprBox(ref inner_init) = initp.node {
224 check_pat(cx, inner, Some(&**inner_init), span, bindings);
226 check_pat(cx, inner, init, span, bindings);
229 check_pat(cx, inner, init, span, bindings);
231 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
232 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
237 fn lint_shadow<'a, 'tcx: 'a>(
238 cx: &LateContext<'a, 'tcx>,
242 init: Option<&'tcx Expr>,
245 if let Some(expr) = init {
246 if is_self_shadow(name, expr) {
252 "`{}` is shadowed by itself in `{}`",
253 snippet(cx, pattern_span, "_"),
254 snippet(cx, expr.span, "..")
257 db.span_note(prev_span, "previous binding is here");
260 } else if contains_name(name, expr) {
266 "`{}` is shadowed by `{}` which reuses the original value",
267 snippet(cx, pattern_span, "_"),
268 snippet(cx, expr.span, "..")
271 db.span_note(expr.span, "initialization happens here");
272 db.span_note(prev_span, "previous binding is here");
281 "`{}` is shadowed by `{}`",
282 snippet(cx, pattern_span, "_"),
283 snippet(cx, expr.span, "..")
286 db.span_note(expr.span, "initialization happens here");
287 db.span_note(prev_span, "previous binding is here");
296 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
298 db.span_note(prev_span, "previous binding is here");
304 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
305 if in_external_macro(cx, expr.span) {
309 ExprUnary(_, ref e) | ExprField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) => {
310 check_expr(cx, e, bindings)
312 ExprBlock(ref block) | ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
315 ExprArray(ref v) | ExprTup(ref v) => for e in v {
316 check_expr(cx, e, bindings)
318 ExprIf(ref cond, ref then, ref otherwise) => {
319 check_expr(cx, cond, bindings);
320 check_expr(cx, &**then, bindings);
321 if let Some(ref o) = *otherwise {
322 check_expr(cx, o, bindings);
325 ExprWhile(ref cond, ref block, _) => {
326 check_expr(cx, cond, bindings);
327 check_block(cx, block, bindings);
329 ExprMatch(ref init, ref arms, _) => {
330 check_expr(cx, init, bindings);
331 let len = bindings.len();
333 for pat in &arm.pats {
334 check_pat(cx, pat, Some(&**init), pat.span, bindings);
335 // This is ugly, but needed to get the right type
336 if let Some(ref guard) = arm.guard {
337 check_expr(cx, guard, bindings);
339 check_expr(cx, &arm.body, bindings);
340 bindings.truncate(len);
348 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
350 TySlice(ref sty) => check_ty(cx, sty, bindings),
351 TyArray(ref fty, body_id) => {
352 check_ty(cx, fty, bindings);
353 check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings);
355 TyPtr(MutTy { ty: ref mty, .. }) | TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
356 TyTup(ref tup) => for t in tup {
357 check_ty(cx, t, bindings)
359 TyTypeof(body_id) => check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings),
364 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
366 ExprBox(ref inner) | ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
367 ExprBlock(ref block) => {
368 block.stmts.is_empty()
372 .map_or(false, |e| is_self_shadow(name, e))
374 ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
375 ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
380 fn path_eq_name(name: Name, path: &Path) -> bool {
381 !path.is_global() && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()