1 use crate::reexport::Name;
2 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
3 use rustc_hir::intravisit::FnKind;
5 Block, Body, Expr, ExprKind, FnDecl, Guard, HirId, Local, MutTy, Pat, PatKind, Path, QPath, StmtKind, Ty, TyKind,
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for bindings that shadow other bindings already in
16 /// scope, while just changing reference level or mutability.
18 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
19 /// code. Still, some may opt to avoid it in their code base, they can set this
22 /// **Known problems:** This lint, as the other shadowing related lints,
23 /// currently only catches very simple patterns.
32 "rebinding a name to itself, e.g., `let mut x = &mut x`"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for bindings that shadow other bindings already in
37 /// scope, while reusing the original value.
39 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
40 /// code. Still, some argue that name shadowing like this hurts readability,
41 /// because a value may be bound to different things depending on position in
44 /// **Known problems:** This lint, as the other shadowing related lints,
45 /// currently only catches very simple patterns.
52 /// use different variable name:
59 "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for bindings that shadow other bindings already in
64 /// scope, either without a initialization or with one that does not even use
65 /// the original value.
67 /// **Why is this bad?** Name shadowing can hurt readability, especially in
68 /// large code bases, because it is easy to lose track of the active binding at
69 /// any place in the code. This can be alleviated by either giving more specific
70 /// names to bindings or introducing more scopes to contain the bindings.
72 /// **Known problems:** This lint, as the other shadowing related lints,
73 /// currently only catches very simple patterns.
80 /// let x = z; // shadows the earlier binding
84 "rebinding a name without even using the original value"
87 declare_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
89 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Shadow {
92 cx: &LateContext<'a, 'tcx>,
94 decl: &'tcx FnDecl<'_>,
99 if in_external_macro(cx.sess(), body.value.span) {
102 check_fn(cx, decl, body);
106 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>) {
107 let mut bindings = Vec::with_capacity(decl.inputs.len());
108 for arg in iter_input_pats(decl, body) {
109 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
110 bindings.push((ident.name, ident.span))
113 check_expr(cx, &body.value, &mut bindings);
116 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block<'_>, bindings: &mut Vec<(Name, Span)>) {
117 let len = bindings.len();
118 for stmt in block.stmts {
120 StmtKind::Local(ref local) => check_local(cx, local, bindings),
121 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => check_expr(cx, e, bindings),
122 StmtKind::Item(..) => {},
125 if let Some(ref o) = block.expr {
126 check_expr(cx, o, bindings);
128 bindings.truncate(len);
131 fn check_local<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Name, Span)>) {
132 if in_external_macro(cx.sess(), local.span) {
135 if higher::is_from_for_desugar(local) {
145 if let Some(ref t) = *ty {
146 check_ty(cx, t, bindings)
148 if let Some(ref o) = *init {
149 check_expr(cx, o, bindings);
150 check_pat(cx, pat, Some(o), span, bindings);
152 check_pat(cx, pat, None, span, bindings);
156 fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
157 let var_ty = cx.tables.node_type_opt(pat_id);
158 if let Some(var_ty) = var_ty {
160 ty::Adt(..) => false,
168 fn check_pat<'a, 'tcx>(
169 cx: &LateContext<'a, 'tcx>,
171 init: Option<&'tcx Expr<'_>>,
173 bindings: &mut Vec<(Name, Span)>,
175 // TODO: match more stuff / destructuring
177 PatKind::Binding(.., ident, ref inner) => {
178 let name = ident.name;
179 if is_binding(cx, pat.hir_id) {
180 let mut new_binding = true;
181 for tup in bindings.iter_mut() {
183 lint_shadow(cx, name, span, pat.span, init, tup.1);
190 bindings.push((name, ident.span));
193 if let Some(ref p) = *inner {
194 check_pat(cx, p, init, span, bindings);
197 PatKind::Struct(_, pfields, _) => {
198 if let Some(init_struct) = init {
199 if let ExprKind::Struct(_, ref efields, _) = init_struct.kind {
200 for field in pfields {
201 let name = field.ident.name;
204 .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
205 check_pat(cx, &field.pat, efield, span, bindings);
208 for field in pfields {
209 check_pat(cx, &field.pat, init, span, bindings);
213 for field in pfields {
214 check_pat(cx, &field.pat, None, span, bindings);
218 PatKind::Tuple(inner, _) => {
219 if let Some(init_tup) = init {
220 if let ExprKind::Tup(ref tup) = init_tup.kind {
221 for (i, p) in inner.iter().enumerate() {
222 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
226 check_pat(cx, p, init, span, bindings);
231 check_pat(cx, p, None, span, bindings);
235 PatKind::Box(ref inner) => {
236 if let Some(initp) = init {
237 if let ExprKind::Box(ref inner_init) = initp.kind {
238 check_pat(cx, inner, Some(&**inner_init), span, bindings);
240 check_pat(cx, inner, init, span, bindings);
243 check_pat(cx, inner, init, span, bindings);
246 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
247 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
252 fn lint_shadow<'a, 'tcx>(
253 cx: &LateContext<'a, 'tcx>,
257 init: Option<&'tcx Expr<'_>>,
260 if let Some(expr) = init {
261 if is_self_shadow(name, expr) {
267 "`{}` is shadowed by itself in `{}`",
268 snippet(cx, pattern_span, "_"),
269 snippet(cx, expr.span, "..")
272 diag.span_note(prev_span, "previous binding is here");
275 } else if contains_name(name, expr) {
281 "`{}` is shadowed by `{}` which reuses the original value",
282 snippet(cx, pattern_span, "_"),
283 snippet(cx, expr.span, "..")
286 diag.span_note(expr.span, "initialization happens here");
287 diag.span_note(prev_span, "previous binding is here");
296 "`{}` is shadowed by `{}`",
297 snippet(cx, pattern_span, "_"),
298 snippet(cx, expr.span, "..")
301 diag.span_note(expr.span, "initialization happens here");
302 diag.span_note(prev_span, "previous binding is here");
311 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
313 diag.span_note(prev_span, "previous binding is here");
319 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) {
320 if in_external_macro(cx.sess(), expr.span) {
324 ExprKind::Unary(_, ref e)
325 | ExprKind::Field(ref e, _)
326 | ExprKind::AddrOf(_, _, ref e)
327 | ExprKind::Box(ref e) => check_expr(cx, e, bindings),
328 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
330 // ExprKind::MethodCall
331 ExprKind::Array(v) | ExprKind::Tup(v) => {
333 check_expr(cx, e, bindings)
336 ExprKind::Match(ref init, arms, _) => {
337 check_expr(cx, init, bindings);
338 let len = bindings.len();
340 check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings);
341 // This is ugly, but needed to get the right type
342 if let Some(ref guard) = arm.guard {
344 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
347 check_expr(cx, &arm.body, bindings);
348 bindings.truncate(len);
355 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Name, Span)>) {
357 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
358 TyKind::Array(ref fty, ref anon_const) => {
359 check_ty(cx, fty, bindings);
360 check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
362 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
363 check_ty(cx, mty, bindings)
365 TyKind::Tup(tup) => {
367 check_ty(cx, t, bindings)
370 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
375 fn is_self_shadow(name: Name, expr: &Expr<'_>) -> bool {
377 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, _, ref inner) => is_self_shadow(name, inner),
378 ExprKind::Block(ref block, _) => {
379 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
381 ExprKind::Unary(op, ref inner) => (UnOp::UnDeref == op) && is_self_shadow(name, inner),
382 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
387 fn path_eq_name(name: Name, path: &Path<'_>) -> bool {
388 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()