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.
33 /// let y = &x; // use different variable name
37 "rebinding a name to itself, e.g., `let mut x = &mut x`"
40 declare_clippy_lint! {
41 /// **What it does:** Checks for bindings that shadow other bindings already in
42 /// scope, while reusing the original value.
44 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
45 /// code. Still, some argue that name shadowing like this hurts readability,
46 /// because a value may be bound to different things depending on position in
49 /// **Known problems:** This lint, as the other shadowing related lints,
50 /// currently only catches very simple patterns.
57 /// use different variable name:
64 "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
67 declare_clippy_lint! {
68 /// **What it does:** Checks for bindings that shadow other bindings already in
69 /// scope, either without a initialization or with one that does not even use
70 /// the original value.
72 /// **Why is this bad?** Name shadowing can hurt readability, especially in
73 /// large code bases, because it is easy to lose track of the active binding at
74 /// any place in the code. This can be alleviated by either giving more specific
75 /// names to bindings or introducing more scopes to contain the bindings.
77 /// **Known problems:** This lint, as the other shadowing related lints,
78 /// currently only catches very simple patterns.
87 /// let x = z; // shadows the earlier binding
90 /// let w = z; // use different variable name
94 "rebinding a name without even using the original value"
97 declare_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
99 impl<'tcx> LateLintPass<'tcx> for Shadow {
102 cx: &LateContext<'tcx>,
104 decl: &'tcx FnDecl<'_>,
105 body: &'tcx Body<'_>,
109 if in_external_macro(cx.sess(), body.value.span) {
112 check_fn(cx, decl, body);
116 fn check_fn<'tcx>(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>) {
117 let mut bindings = Vec::with_capacity(decl.inputs.len());
118 for arg in iter_input_pats(decl, body) {
119 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
120 bindings.push((ident.name, ident.span))
123 check_expr(cx, &body.value, &mut bindings);
126 fn check_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'_>, bindings: &mut Vec<(Name, Span)>) {
127 let len = bindings.len();
128 for stmt in block.stmts {
130 StmtKind::Local(ref local) => check_local(cx, local, bindings),
131 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => check_expr(cx, e, bindings),
132 StmtKind::Item(..) => {},
135 if let Some(ref o) = block.expr {
136 check_expr(cx, o, bindings);
138 bindings.truncate(len);
141 fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Name, Span)>) {
142 if in_external_macro(cx.sess(), local.span) {
145 if higher::is_from_for_desugar(local) {
155 if let Some(ref t) = *ty {
156 check_ty(cx, t, bindings)
158 if let Some(ref o) = *init {
159 check_expr(cx, o, bindings);
160 check_pat(cx, pat, Some(o), span, bindings);
162 check_pat(cx, pat, None, span, bindings);
166 fn is_binding(cx: &LateContext<'_>, pat_id: HirId) -> bool {
167 let var_ty = cx.tables().node_type_opt(pat_id);
168 var_ty.map_or(false, |var_ty| !matches!(var_ty.kind, ty::Adt(..)))
172 cx: &LateContext<'tcx>,
174 init: Option<&'tcx Expr<'_>>,
176 bindings: &mut Vec<(Name, Span)>,
178 // TODO: match more stuff / destructuring
180 PatKind::Binding(.., ident, ref inner) => {
181 let name = ident.name;
182 if is_binding(cx, pat.hir_id) {
183 let mut new_binding = true;
184 for tup in bindings.iter_mut() {
186 lint_shadow(cx, name, span, pat.span, init, tup.1);
193 bindings.push((name, ident.span));
196 if let Some(ref p) = *inner {
197 check_pat(cx, p, init, span, bindings);
200 PatKind::Struct(_, pfields, _) => {
201 if let Some(init_struct) = init {
202 if let ExprKind::Struct(_, ref efields, _) = init_struct.kind {
203 for field in pfields {
204 let name = field.ident.name;
207 .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
208 check_pat(cx, &field.pat, efield, span, bindings);
211 for field in pfields {
212 check_pat(cx, &field.pat, init, span, bindings);
216 for field in pfields {
217 check_pat(cx, &field.pat, None, span, bindings);
221 PatKind::Tuple(inner, _) => {
222 if let Some(init_tup) = init {
223 if let ExprKind::Tup(ref tup) = init_tup.kind {
224 for (i, p) in inner.iter().enumerate() {
225 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
229 check_pat(cx, p, init, span, bindings);
234 check_pat(cx, p, None, span, bindings);
238 PatKind::Box(ref inner) => {
239 if let Some(initp) = init {
240 if let ExprKind::Box(ref inner_init) = initp.kind {
241 check_pat(cx, inner, Some(&**inner_init), span, bindings);
243 check_pat(cx, inner, init, span, bindings);
246 check_pat(cx, inner, init, span, bindings);
249 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
250 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
255 fn lint_shadow<'tcx>(
256 cx: &LateContext<'tcx>,
260 init: Option<&'tcx Expr<'_>>,
263 if let Some(expr) = init {
264 if is_self_shadow(name, expr) {
270 "`{}` is shadowed by itself in `{}`",
271 snippet(cx, pattern_span, "_"),
272 snippet(cx, expr.span, "..")
275 diag.span_note(prev_span, "previous binding is here");
278 } else if contains_name(name, expr) {
284 "`{}` is shadowed by `{}` which reuses the original value",
285 snippet(cx, pattern_span, "_"),
286 snippet(cx, expr.span, "..")
289 diag.span_note(expr.span, "initialization happens here");
290 diag.span_note(prev_span, "previous binding is here");
299 "`{}` is shadowed by `{}`",
300 snippet(cx, pattern_span, "_"),
301 snippet(cx, expr.span, "..")
304 diag.span_note(expr.span, "initialization happens here");
305 diag.span_note(prev_span, "previous binding is here");
314 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
316 diag.span_note(prev_span, "previous binding is here");
322 fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) {
323 if in_external_macro(cx.sess(), expr.span) {
327 ExprKind::Unary(_, ref e)
328 | ExprKind::Field(ref e, _)
329 | ExprKind::AddrOf(_, _, ref e)
330 | ExprKind::Box(ref e) => check_expr(cx, e, bindings),
331 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
333 // ExprKind::MethodCall
334 ExprKind::Array(v) | ExprKind::Tup(v) => {
336 check_expr(cx, e, bindings)
339 ExprKind::Match(ref init, arms, _) => {
340 check_expr(cx, init, bindings);
341 let len = bindings.len();
343 check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings);
344 // This is ugly, but needed to get the right type
345 if let Some(ref guard) = arm.guard {
347 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
350 check_expr(cx, &arm.body, bindings);
351 bindings.truncate(len);
358 fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Name, Span)>) {
360 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
361 TyKind::Array(ref fty, ref anon_const) => {
362 check_ty(cx, fty, bindings);
363 check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
365 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
366 check_ty(cx, mty, bindings)
368 TyKind::Tup(tup) => {
370 check_ty(cx, t, bindings)
373 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
378 fn is_self_shadow(name: Name, expr: &Expr<'_>) -> bool {
380 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, _, ref inner) => is_self_shadow(name, inner),
381 ExprKind::Block(ref block, _) => {
382 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
384 ExprKind::Unary(op, ref inner) => (UnOp::UnDeref == op) && is_self_shadow(name, inner),
385 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
390 fn path_eq_name(name: Name, path: &Path<'_>) -> bool {
391 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()