1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet;
3 use clippy_utils::{contains_name, higher, iter_input_pats};
4 use rustc_hir::intravisit::FnKind;
6 Block, Body, Expr, ExprKind, FnDecl, Guard, HirId, Local, MutTy, Pat, PatKind, Path, QPath, StmtKind, Ty, TyKind,
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Span;
14 use rustc_span::symbol::Symbol;
16 declare_clippy_lint! {
18 /// Checks for bindings that shadow other bindings already in
19 /// scope, while just changing reference level or mutability.
21 /// ### Why is this bad?
22 /// Not much, in fact it's a very common pattern in Rust
23 /// code. Still, some may opt to avoid it in their code base, they can set this
26 /// ### Known problems
27 /// This lint, as the other shadowing related lints,
28 /// currently only catches very simple patterns.
37 /// let y = &x; // use different variable name
41 "rebinding a name to itself, e.g., `let mut x = &mut x`"
44 declare_clippy_lint! {
46 /// Checks for bindings that shadow other bindings already in
47 /// scope, while reusing the original value.
49 /// ### Why is this bad?
50 /// Not too much, in fact it's a common pattern in Rust
51 /// code. Still, some argue that name shadowing like this hurts readability,
52 /// because a value may be bound to different things depending on position in
55 /// ### Known problems
56 /// This lint, as the other shadowing related lints,
57 /// currently only catches very simple patterns.
64 /// use different variable name:
71 "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
74 declare_clippy_lint! {
76 /// Checks for bindings that shadow other bindings already in
77 /// scope, either without a initialization or with one that does not even use
78 /// the original value.
80 /// ### Why is this bad?
81 /// Name shadowing can hurt readability, especially in
82 /// large code bases, because it is easy to lose track of the active binding at
83 /// any place in the code. This can be alleviated by either giving more specific
84 /// names to bindings or introducing more scopes to contain the bindings.
86 /// ### Known problems
87 /// This lint, as the other shadowing related lints,
88 /// currently only catches very simple patterns. Note that
89 /// `allow`/`warn`/`deny`/`forbid` attributes only work on the function level
99 /// let x = z; // shadows the earlier binding
102 /// let w = z; // use different variable name
104 pub SHADOW_UNRELATED,
106 "rebinding a name without even using the original value"
109 declare_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
111 impl<'tcx> LateLintPass<'tcx> for Shadow {
114 cx: &LateContext<'tcx>,
116 decl: &'tcx FnDecl<'_>,
117 body: &'tcx Body<'_>,
121 if in_external_macro(cx.sess(), body.value.span) {
124 check_fn(cx, decl, body);
128 fn check_fn<'tcx>(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>) {
129 let mut bindings = Vec::with_capacity(decl.inputs.len());
130 for arg in iter_input_pats(decl, body) {
131 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
132 bindings.push((ident.name, ident.span));
135 check_expr(cx, &body.value, &mut bindings);
138 fn check_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'_>, bindings: &mut Vec<(Symbol, Span)>) {
139 let len = bindings.len();
140 for stmt in block.stmts {
142 StmtKind::Local(local) => check_local(cx, local, bindings),
143 StmtKind::Expr(e) | StmtKind::Semi(e) => check_expr(cx, e, bindings),
144 StmtKind::Item(..) => {},
147 if let Some(o) = block.expr {
148 check_expr(cx, o, bindings);
150 bindings.truncate(len);
153 fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Symbol, Span)>) {
154 if in_external_macro(cx.sess(), local.span) {
157 if higher::is_from_for_desugar(local) {
167 if let Some(t) = *ty {
168 check_ty(cx, t, bindings);
170 if let Some(o) = *init {
171 check_expr(cx, o, bindings);
172 check_pat(cx, pat, Some(o), span, bindings);
174 check_pat(cx, pat, None, span, bindings);
178 fn is_binding(cx: &LateContext<'_>, pat_id: HirId) -> bool {
179 let var_ty = cx.typeck_results().node_type_opt(pat_id);
180 var_ty.map_or(false, |var_ty| !matches!(var_ty.kind(), ty::Adt(..)))
184 cx: &LateContext<'tcx>,
186 init: Option<&'tcx Expr<'_>>,
188 bindings: &mut Vec<(Symbol, Span)>,
190 // TODO: match more stuff / destructuring
192 PatKind::Binding(.., ident, ref inner) => {
193 let name = ident.name;
194 if is_binding(cx, pat.hir_id) {
195 let mut new_binding = true;
196 for tup in bindings.iter_mut() {
198 lint_shadow(cx, name, span, pat.span, init, tup.1);
205 bindings.push((name, ident.span));
208 if let Some(p) = *inner {
209 check_pat(cx, p, init, span, bindings);
212 PatKind::Struct(_, pfields, _) => {
213 if let Some(init_struct) = init {
214 if let ExprKind::Struct(_, efields, _) = init_struct.kind {
215 for field in pfields {
216 let name = field.ident.name;
219 .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
220 check_pat(cx, field.pat, efield, span, bindings);
223 for field in pfields {
224 check_pat(cx, field.pat, init, span, bindings);
228 for field in pfields {
229 check_pat(cx, field.pat, None, span, bindings);
233 PatKind::Tuple(inner, _) => {
234 if let Some(init_tup) = init {
235 if let ExprKind::Tup(tup) = init_tup.kind {
236 for (i, p) in inner.iter().enumerate() {
237 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
241 check_pat(cx, p, init, span, bindings);
246 check_pat(cx, p, None, span, bindings);
250 PatKind::Box(inner) => {
251 if let Some(initp) = init {
252 if let ExprKind::Box(inner_init) = initp.kind {
253 check_pat(cx, inner, Some(inner_init), span, bindings);
255 check_pat(cx, inner, init, span, bindings);
258 check_pat(cx, inner, init, span, bindings);
261 PatKind::Ref(inner, _) => check_pat(cx, inner, init, span, bindings),
262 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
267 fn lint_shadow<'tcx>(
268 cx: &LateContext<'tcx>,
272 init: Option<&'tcx Expr<'_>>,
275 if let Some(expr) = init {
276 if is_self_shadow(name, expr) {
282 "`{}` is shadowed by itself in `{}`",
283 snippet(cx, pattern_span, "_"),
284 snippet(cx, expr.span, "..")
287 diag.span_note(prev_span, "previous binding is here");
290 } else if contains_name(name, expr) {
296 "`{}` is shadowed by `{}` which reuses the original value",
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");
310 &format!("`{}` is being shadowed", snippet(cx, pattern_span, "_")),
312 diag.span_note(expr.span, "initialization happens here");
313 diag.span_note(prev_span, "previous binding is here");
322 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
324 diag.span_note(prev_span, "previous binding is here");
330 fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Symbol, Span)>) {
331 if in_external_macro(cx.sess(), expr.span) {
335 ExprKind::Unary(_, e) | ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) | ExprKind::Box(e) => {
336 check_expr(cx, e, bindings);
338 ExprKind::Block(block, _) | ExprKind::Loop(block, ..) => check_block(cx, block, bindings),
340 // ExprKind::MethodCall
341 ExprKind::Array(v) | ExprKind::Tup(v) => {
343 check_expr(cx, e, bindings);
346 ExprKind::If(cond, then, ref otherwise) => {
347 check_expr(cx, cond, bindings);
348 check_expr(cx, then, bindings);
349 if let Some(o) = *otherwise {
350 check_expr(cx, o, bindings);
353 ExprKind::Match(init, arms, _) => {
354 check_expr(cx, init, bindings);
355 let len = bindings.len();
357 check_pat(cx, arm.pat, Some(init), arm.pat.span, bindings);
358 // This is ugly, but needed to get the right type
359 if let Some(ref guard) = arm.guard {
361 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
362 Guard::IfLet(guard_pat, guard_expr) => {
363 check_pat(cx, guard_pat, Some(*guard_expr), guard_pat.span, bindings);
364 check_expr(cx, guard_expr, bindings);
368 check_expr(cx, arm.body, bindings);
369 bindings.truncate(len);
376 fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Symbol, Span)>) {
378 TyKind::Slice(sty) => check_ty(cx, sty, bindings),
379 TyKind::Array(fty, ref anon_const) => {
380 check_ty(cx, fty, bindings);
381 check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
383 TyKind::Ptr(MutTy { ty: mty, .. }) | TyKind::Rptr(_, MutTy { ty: mty, .. }) => check_ty(cx, mty, bindings),
384 TyKind::Tup(tup) => {
386 check_ty(cx, t, bindings);
389 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
394 fn is_self_shadow(name: Symbol, expr: &Expr<'_>) -> bool {
396 ExprKind::Box(inner) | ExprKind::AddrOf(_, _, inner) => is_self_shadow(name, inner),
397 ExprKind::Block(block, _) => {
398 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
400 ExprKind::Unary(op, inner) => (UnOp::Deref == op) && is_self_shadow(name, inner),
401 ExprKind::Path(QPath::Resolved(_, path)) => path_eq_name(name, path),
406 fn path_eq_name(name: Symbol, path: &Path<'_>) -> bool {
407 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.name == name