3 use rustc::hir::def::Def;
5 use rustc::hir::intravisit::{Visitor, FnKind};
7 use syntax::codemap::Span;
8 use utils::{higher, in_external_macro, snippet, span_lint_and_then};
10 /// **What it does:** Checks for bindings that shadow other bindings already in
11 /// scope, while just changing reference level or mutability.
13 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
14 /// code. Still, some may opt to avoid it in their code base, they can set this
17 /// **Known problems:** This lint, as the other shadowing related lints,
18 /// currently only catches very simple patterns.
27 "rebinding a name to itself, e.g. `let mut x = &mut x`"
30 /// **What it does:** Checks for bindings that shadow other bindings already in
31 /// scope, while reusing the original value.
33 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
34 /// code. Still, some argue that name shadowing like this hurts readability,
35 /// because a value may be bound to different things depending on position in
38 /// **Known problems:** This lint, as the other shadowing related lints,
39 /// currently only catches very simple patterns.
48 "rebinding a name to an expression that re-uses the original value, e.g. \
52 /// **What it does:** Checks for bindings that shadow other bindings already in
53 /// scope, either without a initialization or with one that does not even use
54 /// the original value.
56 /// **Why is this bad?** Name shadowing can hurt readability, especially in
57 /// large code bases, because it is easy to lose track of the active binding at
58 /// any place in the code. This can be alleviated by either giving more specific
59 /// names to bindings ore introducing more scopes to contain the bindings.
61 /// **Known problems:** This lint, as the other shadowing related lints,
62 /// currently only catches very simple patterns.
66 /// let x = y; let x = z; // shadows the earlier binding
71 "rebinding a name without even using the original value"
74 #[derive(Copy, Clone)]
77 impl LintPass for Pass {
78 fn get_lints(&self) -> LintArray {
79 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
83 impl LateLintPass for Pass {
84 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, block: &Block, _: Span, _: NodeId) {
85 if in_external_macro(cx, block.span) {
88 check_fn(cx, decl, block);
92 fn check_fn(cx: &LateContext, decl: &FnDecl, block: &Block) {
93 let mut bindings = Vec::new();
94 for arg in &decl.inputs {
95 if let PatKind::Binding(_, ident, _) = arg.pat.node {
96 bindings.push((ident.node, ident.span))
99 check_block(cx, block, &mut bindings);
102 fn check_block(cx: &LateContext, block: &Block, bindings: &mut Vec<(Name, Span)>) {
103 let len = bindings.len();
104 for stmt in &block.stmts {
106 StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
108 StmtSemi(ref e, _) => check_expr(cx, e, bindings),
111 if let Some(ref o) = block.expr {
112 check_expr(cx, o, bindings);
114 bindings.truncate(len);
117 fn check_decl(cx: &LateContext, decl: &Decl, bindings: &mut Vec<(Name, Span)>) {
118 if in_external_macro(cx, decl.span) {
121 if higher::is_from_for_desugar(decl) {
124 if let DeclLocal(ref local) = decl.node {
125 let Local { ref pat, ref ty, ref init, span, .. } = **local;
126 if let Some(ref t) = *ty {
127 check_ty(cx, t, bindings)
129 if let Some(ref o) = *init {
130 check_expr(cx, o, bindings);
131 check_pat(cx, pat, &Some(o), span, bindings);
133 check_pat(cx, pat, &None, span, bindings);
138 fn is_binding(cx: &LateContext, pat: &Pat) -> bool {
139 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
140 Some(Def::Variant(..)) |
141 Some(Def::Struct(..)) => false,
146 fn check_pat(cx: &LateContext, pat: &Pat, init: &Option<&Expr>, span: Span, bindings: &mut Vec<(Name, Span)>) {
147 // TODO: match more stuff / destructuring
149 PatKind::Binding(_, ref ident, ref inner) => {
150 let name = ident.node;
151 if is_binding(cx, pat) {
152 let mut new_binding = true;
153 for tup in bindings.iter_mut() {
155 lint_shadow(cx, name, span, pat.span, init, tup.1);
162 bindings.push((name, ident.span));
165 if let Some(ref p) = *inner {
166 check_pat(cx, p, init, span, bindings);
169 PatKind::Struct(_, ref pfields, _) => {
170 if let Some(init_struct) = *init {
171 if let ExprStruct(_, ref efields, _) = init_struct.node {
172 for field in pfields {
173 let name = field.node.name;
174 let efield = efields.iter()
175 .find(|f| f.name.node == name)
177 check_pat(cx, &field.node.pat, &efield, span, bindings);
180 for field in pfields {
181 check_pat(cx, &field.node.pat, init, span, bindings);
185 for field in pfields {
186 check_pat(cx, &field.node.pat, &None, span, bindings);
190 PatKind::Tuple(ref inner, _) => {
191 if let Some(init_tup) = *init {
192 if let ExprTup(ref tup) = init_tup.node {
193 for (i, p) in inner.iter().enumerate() {
194 check_pat(cx, p, &Some(&tup[i]), p.span, bindings);
198 check_pat(cx, p, init, span, bindings);
203 check_pat(cx, p, &None, span, bindings);
207 PatKind::Box(ref inner) => {
208 if let Some(initp) = *init {
209 if let ExprBox(ref inner_init) = initp.node {
210 check_pat(cx, inner, &Some(&**inner_init), span, bindings);
212 check_pat(cx, inner, init, span, bindings);
215 check_pat(cx, inner, init, span, bindings);
218 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
219 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
224 fn lint_shadow<T>(cx: &LateContext, name: Name, span: Span, pattern_span: Span, init: &Option<T>, prev_span: Span)
225 where T: Deref<Target = Expr>
227 if let Some(ref expr) = *init {
228 if is_self_shadow(name, expr) {
229 span_lint_and_then(cx,
232 &format!("`{}` is shadowed by itself in `{}`",
233 snippet(cx, pattern_span, "_"),
234 snippet(cx, expr.span, "..")),
235 |db| { db.span_note(prev_span, "previous binding is here"); },
237 } else if contains_self(name, expr) {
238 span_lint_and_then(cx,
241 &format!("`{}` is shadowed by `{}` which reuses the original value",
242 snippet(cx, pattern_span, "_"),
243 snippet(cx, expr.span, "..")),
245 db.span_note(expr.span, "initialization happens here");
246 db.span_note(prev_span, "previous binding is here");
249 span_lint_and_then(cx,
252 &format!("`{}` is shadowed by `{}`",
253 snippet(cx, pattern_span, "_"),
254 snippet(cx, expr.span, "..")),
256 db.span_note(expr.span, "initialization happens here");
257 db.span_note(prev_span, "previous binding is here");
262 span_lint_and_then(cx,
265 &format!("{} shadows a previous declaration", snippet(cx, pattern_span, "_")),
266 |db| { db.span_note(prev_span, "previous binding is here"); });
270 fn check_expr(cx: &LateContext, expr: &Expr, bindings: &mut Vec<(Name, Span)>) {
271 if in_external_macro(cx, expr.span) {
275 ExprUnary(_, ref e) |
276 ExprField(ref e, _) |
277 ExprTupField(ref e, _) |
278 ExprAddrOf(_, ref e) |
279 ExprBox(ref e) => check_expr(cx, e, bindings),
280 ExprBlock(ref block) |
281 ExprLoop(ref block, _) => check_block(cx, block, bindings),
284 ExprVec(ref v) | ExprTup(ref v) => {
286 check_expr(cx, e, bindings)
289 ExprIf(ref cond, ref then, ref otherwise) => {
290 check_expr(cx, cond, bindings);
291 check_block(cx, then, bindings);
292 if let Some(ref o) = *otherwise {
293 check_expr(cx, o, bindings);
296 ExprWhile(ref cond, ref block, _) => {
297 check_expr(cx, cond, bindings);
298 check_block(cx, block, bindings);
300 ExprMatch(ref init, ref arms, _) => {
301 check_expr(cx, init, bindings);
302 let len = bindings.len();
304 for pat in &arm.pats {
305 check_pat(cx, pat, &Some(&**init), pat.span, bindings);
306 // This is ugly, but needed to get the right type
307 if let Some(ref guard) = arm.guard {
308 check_expr(cx, guard, bindings);
310 check_expr(cx, &arm.body, bindings);
311 bindings.truncate(len);
319 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
321 TyObjectSum(ref sty, _) |
322 TyVec(ref sty) => check_ty(cx, sty, bindings),
323 TyFixedLengthVec(ref fty, ref expr) => {
324 check_ty(cx, fty, bindings);
325 check_expr(cx, expr, bindings);
327 TyPtr(MutTy { ty: ref mty, .. }) |
328 TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
331 check_ty(cx, t, bindings)
334 TyTypeof(ref expr) => check_expr(cx, expr, bindings),
339 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
342 ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
343 ExprBlock(ref block) => {
344 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
346 ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
347 ExprPath(_, ref path) => path_eq_name(name, path),
352 fn path_eq_name(name: Name, path: &Path) -> bool {
353 !path.global && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
356 struct ContainsSelf {
361 impl<'v> Visitor<'v> for ContainsSelf {
362 fn visit_name(&mut self, _: Span, name: Name) {
363 if self.name == name {
369 fn contains_self(name: Name, expr: &Expr) -> bool {
370 let mut cs = ContainsSelf {