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 if let Some(var_ty) = var_ty {
170 ty::Adt(..) => false,
179 cx: &LateContext<'tcx>,
181 init: Option<&'tcx Expr<'_>>,
183 bindings: &mut Vec<(Name, Span)>,
185 // TODO: match more stuff / destructuring
187 PatKind::Binding(.., ident, ref inner) => {
188 let name = ident.name;
189 if is_binding(cx, pat.hir_id) {
190 let mut new_binding = true;
191 for tup in bindings.iter_mut() {
193 lint_shadow(cx, name, span, pat.span, init, tup.1);
200 bindings.push((name, ident.span));
203 if let Some(ref p) = *inner {
204 check_pat(cx, p, init, span, bindings);
207 PatKind::Struct(_, pfields, _) => {
208 if let Some(init_struct) = init {
209 if let ExprKind::Struct(_, ref efields, _) = init_struct.kind {
210 for field in pfields {
211 let name = field.ident.name;
214 .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
215 check_pat(cx, &field.pat, efield, span, bindings);
218 for field in pfields {
219 check_pat(cx, &field.pat, init, span, bindings);
223 for field in pfields {
224 check_pat(cx, &field.pat, None, span, bindings);
228 PatKind::Tuple(inner, _) => {
229 if let Some(init_tup) = init {
230 if let ExprKind::Tup(ref tup) = init_tup.kind {
231 for (i, p) in inner.iter().enumerate() {
232 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
236 check_pat(cx, p, init, span, bindings);
241 check_pat(cx, p, None, span, bindings);
245 PatKind::Box(ref inner) => {
246 if let Some(initp) = init {
247 if let ExprKind::Box(ref inner_init) = initp.kind {
248 check_pat(cx, inner, Some(&**inner_init), span, bindings);
250 check_pat(cx, inner, init, span, bindings);
253 check_pat(cx, inner, init, span, bindings);
256 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
257 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
262 fn lint_shadow<'tcx>(
263 cx: &LateContext<'tcx>,
267 init: Option<&'tcx Expr<'_>>,
270 if let Some(expr) = init {
271 if is_self_shadow(name, expr) {
277 "`{}` is shadowed by itself in `{}`",
278 snippet(cx, pattern_span, "_"),
279 snippet(cx, expr.span, "..")
282 diag.span_note(prev_span, "previous binding is here");
285 } else if contains_name(name, expr) {
291 "`{}` is shadowed by `{}` which reuses the original value",
292 snippet(cx, pattern_span, "_"),
293 snippet(cx, expr.span, "..")
296 diag.span_note(expr.span, "initialization happens here");
297 diag.span_note(prev_span, "previous binding is here");
306 "`{}` is shadowed by `{}`",
307 snippet(cx, pattern_span, "_"),
308 snippet(cx, expr.span, "..")
311 diag.span_note(expr.span, "initialization happens here");
312 diag.span_note(prev_span, "previous binding is here");
321 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
323 diag.span_note(prev_span, "previous binding is here");
329 fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) {
330 if in_external_macro(cx.sess(), expr.span) {
334 ExprKind::Unary(_, ref e)
335 | ExprKind::Field(ref e, _)
336 | ExprKind::AddrOf(_, _, ref e)
337 | ExprKind::Box(ref e) => check_expr(cx, e, bindings),
338 ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
340 // ExprKind::MethodCall
341 ExprKind::Array(v) | ExprKind::Tup(v) => {
343 check_expr(cx, e, bindings)
346 ExprKind::Match(ref init, arms, _) => {
347 check_expr(cx, init, bindings);
348 let len = bindings.len();
350 check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings);
351 // This is ugly, but needed to get the right type
352 if let Some(ref guard) = arm.guard {
354 Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
357 check_expr(cx, &arm.body, bindings);
358 bindings.truncate(len);
365 fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Name, Span)>) {
367 TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
368 TyKind::Array(ref fty, ref anon_const) => {
369 check_ty(cx, fty, bindings);
370 check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
372 TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
373 check_ty(cx, mty, bindings)
375 TyKind::Tup(tup) => {
377 check_ty(cx, t, bindings)
380 TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
385 fn is_self_shadow(name: Name, expr: &Expr<'_>) -> bool {
387 ExprKind::Box(ref inner) | ExprKind::AddrOf(_, _, ref inner) => is_self_shadow(name, inner),
388 ExprKind::Block(ref block, _) => {
389 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
391 ExprKind::Unary(op, ref inner) => (UnOp::UnDeref == op) && is_self_shadow(name, inner),
392 ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
397 fn path_eq_name(name: Name, path: &Path<'_>) -> bool {
398 !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()