rust/clippy_lints/src/shadow.rs

395 lines
13 KiB
Rust
Raw Normal View History

2018-05-30 03:15:50 -05:00
use crate::reexport::*;
2018-07-24 01:55:38 -05:00
use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
use rustc::hir::intravisit::FnKind;
use rustc::hir::*;
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
use rustc::ty;
use rustc::{declare_tool_lint, lint_array};
use syntax::source_map::Span;
2015-08-21 10:11:34 -05:00
/// **What it does:** Checks for bindings that shadow other bindings already in
/// scope, while just changing reference level or mutability.
///
/// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
/// code. Still, some may opt to avoid it in their code base, they can set this
/// lint to `Warn`.
///
/// **Known problems:** This lint, as the other shadowing related lints,
/// currently only catches very simple patterns.
///
2016-07-15 17:25:44 -05:00
/// **Example:**
/// ```rust
/// let x = &x;
/// ```
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
pub SHADOW_SAME,
2018-03-28 08:24:26 -05:00
restriction,
"rebinding a name to itself, e.g. `let mut x = &mut x`"
}
/// **What it does:** Checks for bindings that shadow other bindings already in
/// scope, while reusing the original value.
///
/// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
/// code. Still, some argue that name shadowing like this hurts readability,
/// because a value may be bound to different things depending on position in
/// the code.
///
/// **Known problems:** This lint, as the other shadowing related lints,
/// currently only catches very simple patterns.
///
2016-07-15 17:25:44 -05:00
/// **Example:**
/// ```rust
/// let x = x + 1;
/// ```
/// use different variable name:
/// ```rust
/// let y = x + 1;
/// ```
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
2018-11-27 14:49:09 -06:00
pub SHADOW_REUSE,
restriction,
"rebinding a name to an expression that re-uses the original value, e.g. `let x = x + 1`"
}
/// **What it does:** Checks for bindings that shadow other bindings already in
/// scope, either without a initialization or with one that does not even use
/// the original value.
///
/// **Why is this bad?** Name shadowing can hurt readability, especially in
/// large code bases, because it is easy to lose track of the active binding at
/// any place in the code. This can be alleviated by either giving more specific
2018-05-13 06:47:54 -05:00
/// names to bindings or introducing more scopes to contain the bindings.
///
/// **Known problems:** This lint, as the other shadowing related lints,
/// currently only catches very simple patterns.
///
2016-07-15 17:25:44 -05:00
/// **Example:**
/// ```rust
2018-11-27 14:14:15 -06:00
/// let x = y;
/// let x = z; // shadows the earlier binding
2016-07-15 17:25:44 -05:00
/// ```
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
pub SHADOW_UNRELATED,
2018-08-09 11:26:22 -05:00
pedantic,
"rebinding a name without even using the original value"
}
2015-08-21 10:11:34 -05:00
#[derive(Copy, Clone)]
2016-06-10 09:17:20 -05:00
pub struct Pass;
2015-08-21 10:11:34 -05:00
2016-06-10 09:17:20 -05:00
impl LintPass for Pass {
2015-08-21 10:11:34 -05:00
fn get_lints(&self) -> LintArray {
2015-08-21 10:11:34 -05:00
lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
2015-08-21 10:11:34 -05:00
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_fn(
&mut self,
cx: &LateContext<'a, 'tcx>,
_: FnKind<'tcx>,
decl: &'tcx FnDecl,
body: &'tcx Body,
_: Span,
2017-08-09 02:30:56 -05:00
_: NodeId,
) {
2018-07-24 01:55:38 -05:00
if in_external_macro(cx.sess(), body.value.span) {
2016-01-03 22:26:12 -06:00
return;
}
check_fn(cx, decl, body);
2015-08-21 10:11:34 -05:00
}
}
fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
2015-08-21 10:11:34 -05:00
let mut bindings = Vec::new();
for arg in iter_input_pats(decl, body) {
if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
2018-06-28 08:46:58 -05:00
bindings.push((ident.name, ident.span))
2015-08-21 10:11:34 -05:00
}
}
check_expr(cx, &body.value, &mut bindings);
2015-08-21 10:11:34 -05:00
}
fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
2015-08-21 10:11:34 -05:00
let len = bindings.len();
for stmt in &block.stmts {
match stmt.node {
2018-07-12 03:53:53 -05:00
StmtKind::Decl(ref decl, _) => check_decl(cx, decl, bindings),
StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => check_expr(cx, e, bindings),
2015-08-21 10:11:34 -05:00
}
}
2016-01-03 22:26:12 -06:00
if let Some(ref o) = block.expr {
check_expr(cx, o, bindings);
}
2015-08-21 10:11:34 -05:00
bindings.truncate(len);
}
fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
2018-07-24 01:55:38 -05:00
if in_external_macro(cx.sess(), decl.span) {
2016-01-03 22:26:12 -06:00
return;
}
2016-06-29 17:08:43 -05:00
if higher::is_from_for_desugar(decl) {
2016-01-03 22:26:12 -06:00
return;
}
2018-07-16 08:07:39 -05:00
if let DeclKind::Local(ref local) = decl.node {
2017-08-09 02:30:56 -05:00
let Local {
ref pat,
ref ty,
ref init,
span,
..
} = **local;
2016-01-03 22:26:12 -06:00
if let Some(ref t) = *ty {
check_ty(cx, t, bindings)
}
2015-11-24 11:44:40 -06:00
if let Some(ref o) = *init {
2015-09-01 18:36:37 -05:00
check_expr(cx, o, bindings);
check_pat(cx, pat, Some(o), span, bindings);
2015-09-01 18:36:37 -05:00
} else {
check_pat(cx, pat, None, span, bindings);
2015-09-01 18:36:37 -05:00
}
2015-08-21 10:11:34 -05:00
}
}
2018-07-23 06:01:12 -05:00
fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool {
2017-01-13 10:04:56 -06:00
let var_ty = cx.tables.node_id_to_type(pat_id);
match var_ty.sty {
ty::Adt(..) => false,
2016-01-03 22:26:12 -06:00
_ => true,
}
}
fn check_pat<'a, 'tcx>(
cx: &LateContext<'a, 'tcx>,
pat: &'tcx Pat,
init: Option<&'tcx Expr>,
span: Span,
2017-08-09 02:30:56 -05:00
bindings: &mut Vec<(Name, Span)>,
) {
2016-01-03 22:26:12 -06:00
// TODO: match more stuff / destructuring
2015-08-21 10:11:34 -05:00
match pat.node {
2018-06-28 08:46:58 -05:00
PatKind::Binding(_, _, ident, ref inner) => {
let name = ident.name;
2017-08-15 04:10:49 -05:00
if is_binding(cx, pat.hir_id) {
let mut new_binding = true;
for tup in bindings.iter_mut() {
if tup.0 == name {
lint_shadow(cx, name, span, pat.span, init, tup.1);
tup.1 = ident.span;
new_binding = false;
break;
}
}
if new_binding {
bindings.push((name, ident.span));
2015-08-21 10:11:34 -05:00
}
2015-08-21 10:11:34 -05:00
}
2016-01-03 22:26:12 -06:00
if let Some(ref p) = *inner {
check_pat(cx, p, init, span, bindings);
}
2016-12-20 11:21:30 -06:00
},
2018-11-27 14:14:15 -06:00
PatKind::Struct(_, ref pfields, _) => {
if let Some(init_struct) = init {
if let ExprKind::Struct(_, ref efields, _) = init_struct.node {
for field in pfields {
let name = field.node.ident.name;
let efield = efields.iter().find(|f| f.ident.name == name).map(|f| &*f.expr);
check_pat(cx, &field.node.pat, efield, span, bindings);
}
} else {
for field in pfields {
check_pat(cx, &field.node.pat, init, span, bindings);
}
2015-09-01 18:36:37 -05:00
}
} else {
for field in pfields {
2018-11-27 14:14:15 -06:00
check_pat(cx, &field.node.pat, None, span, bindings);
2015-09-01 18:36:37 -05:00
}
2016-01-03 22:26:12 -06:00
}
2016-12-20 11:21:30 -06:00
},
2018-11-27 14:14:15 -06:00
PatKind::Tuple(ref inner, _) => {
if let Some(init_tup) = init {
if let ExprKind::Tup(ref tup) = init_tup.node {
for (i, p) in inner.iter().enumerate() {
check_pat(cx, p, Some(&tup[i]), p.span, bindings);
}
} else {
for p in inner {
check_pat(cx, p, init, span, bindings);
}
2015-09-01 18:36:37 -05:00
}
} else {
for p in inner {
2018-11-27 14:14:15 -06:00
check_pat(cx, p, None, span, bindings);
2015-09-01 18:36:37 -05:00
}
2016-01-03 22:26:12 -06:00
}
2016-12-20 11:21:30 -06:00
},
2018-11-27 14:14:15 -06:00
PatKind::Box(ref inner) => {
if let Some(initp) = init {
if let ExprKind::Box(ref inner_init) = initp.node {
check_pat(cx, inner, Some(&**inner_init), span, bindings);
} else {
check_pat(cx, inner, init, span, bindings);
}
2015-08-21 10:11:34 -05:00
} else {
check_pat(cx, inner, init, span, bindings);
}
2016-12-20 11:21:30 -06:00
},
PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
2016-01-03 22:26:12 -06:00
// PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
2015-08-21 10:11:34 -05:00
_ => (),
}
2015-08-21 10:11:34 -05:00
}
fn lint_shadow<'a, 'tcx: 'a>(
cx: &LateContext<'a, 'tcx>,
name: Name,
span: Span,
pattern_span: Span,
init: Option<&'tcx Expr>,
2017-08-09 02:30:56 -05:00
prev_span: Span,
) {
if let Some(expr) = init {
2015-08-21 10:11:34 -05:00
if is_self_shadow(name, expr) {
2017-08-09 02:30:56 -05:00
span_lint_and_then(
cx,
SHADOW_SAME,
span,
&format!(
"`{}` is shadowed by itself in `{}`",
snippet(cx, pattern_span, "_"),
snippet(cx, expr.span, "..")
),
2017-11-04 14:55:56 -05:00
|db| {
db.span_note(prev_span, "previous binding is here");
},
2017-08-09 02:30:56 -05:00
);
} else if contains_name(name, expr) {
2017-08-09 02:30:56 -05:00
span_lint_and_then(
cx,
SHADOW_REUSE,
pattern_span,
&format!(
"`{}` is shadowed by `{}` which reuses the original value",
snippet(cx, pattern_span, "_"),
snippet(cx, expr.span, "..")
),
|db| {
db.span_note(expr.span, "initialization happens here");
db.span_note(prev_span, "previous binding is here");
},
);
2015-08-21 10:11:34 -05:00
} else {
2017-08-09 02:30:56 -05:00
span_lint_and_then(
cx,
SHADOW_UNRELATED,
pattern_span,
&format!(
"`{}` is shadowed by `{}`",
snippet(cx, pattern_span, "_"),
snippet(cx, expr.span, "..")
),
|db| {
db.span_note(expr.span, "initialization happens here");
db.span_note(prev_span, "previous binding is here");
},
);
2015-08-21 10:11:34 -05:00
}
2015-08-21 10:11:34 -05:00
} else {
2017-09-05 04:33:04 -05:00
span_lint_and_then(
cx,
SHADOW_UNRELATED,
span,
&format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
2017-11-04 14:55:56 -05:00
|db| {
db.span_note(prev_span, "previous binding is here");
},
2017-09-05 04:33:04 -05:00
);
2015-08-21 10:11:34 -05:00
}
}
fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
2018-07-24 01:55:38 -05:00
if in_external_macro(cx.sess(), expr.span) {
2016-01-03 22:26:12 -06:00
return;
}
2015-08-21 10:11:34 -05:00
match expr.node {
2018-07-12 02:30:57 -05:00
ExprKind::Unary(_, ref e) | ExprKind::Field(ref e, _) | ExprKind::AddrOf(_, ref e) | ExprKind::Box(ref e) => {
2017-09-05 04:33:04 -05:00
check_expr(cx, e, bindings)
},
2018-07-12 02:30:57 -05:00
ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
// ExprKind::Call
// ExprKind::MethodCall
2018-11-27 14:14:15 -06:00
ExprKind::Array(ref v) | ExprKind::Tup(ref v) => {
for e in v {
check_expr(cx, e, bindings)
}
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:30:57 -05:00
ExprKind::If(ref cond, ref then, ref otherwise) => {
2015-08-21 10:11:34 -05:00
check_expr(cx, cond, bindings);
check_expr(cx, &**then, bindings);
2016-01-03 22:26:12 -06:00
if let Some(ref o) = *otherwise {
check_expr(cx, o, bindings);
}
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:30:57 -05:00
ExprKind::While(ref cond, ref block, _) => {
2015-08-21 10:11:34 -05:00
check_expr(cx, cond, bindings);
check_block(cx, block, bindings);
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:30:57 -05:00
ExprKind::Match(ref init, ref arms, _) => {
2015-08-21 10:11:34 -05:00
check_expr(cx, init, bindings);
2015-08-25 16:48:22 -05:00
let len = bindings.len();
2016-08-01 09:59:14 -05:00
for arm in arms {
for pat in &arm.pats {
check_pat(cx, pat, Some(&**init), pat.span, bindings);
2016-01-03 22:26:12 -06:00
// This is ugly, but needed to get the right type
if let Some(ref guard) = arm.guard {
2018-09-02 02:38:25 -05:00
match guard {
Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
}
}
check_expr(cx, &arm.body, bindings);
bindings.truncate(len);
2015-08-21 10:11:34 -05:00
}
2015-08-21 10:11:34 -05:00
}
2016-12-20 11:21:30 -06:00
},
2016-01-03 22:26:12 -06:00
_ => (),
2015-08-21 10:11:34 -05:00
}
}
fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
2015-08-21 10:11:34 -05:00
match ty.node {
2018-07-12 03:03:06 -05:00
TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
TyKind::Array(ref fty, ref anon_const) => {
2015-08-21 10:11:34 -05:00
check_ty(cx, fty, bindings);
check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
2016-12-20 11:21:30 -06:00
},
2018-11-27 14:14:15 -06:00
TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
check_ty(cx, mty, bindings)
},
TyKind::Tup(ref tup) => {
for t in tup {
check_ty(cx, t, bindings)
}
2016-12-20 11:21:30 -06:00
},
TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
2015-08-21 10:11:34 -05:00
_ => (),
}
}
fn is_self_shadow(name: Name, expr: &Expr) -> bool {
match expr.node {
2018-07-12 02:30:57 -05:00
ExprKind::Box(ref inner) | ExprKind::AddrOf(_, ref inner) => is_self_shadow(name, inner),
ExprKind::Block(ref block, _) => {
2018-11-27 14:14:15 -06:00
block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:30:57 -05:00
ExprKind::Unary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
2015-08-21 10:11:34 -05:00
_ => false,
}
}
2015-08-21 10:11:34 -05:00
fn path_eq_name(name: Name, path: &Path) -> bool {
2018-06-28 08:46:58 -05:00
!path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
2015-08-21 10:11:34 -05:00
}