]> git.lizzy.rs Git - rust.git/blob - src/shadow.rs
25970df399db90859d9f3acc08a5922e7425aa08
[rust.git] / src / shadow.rs
1 use std::ops::Deref;
2 use rustc_front::hir::*;
3 use reexport::*;
4 use syntax::codemap::Span;
5 use rustc_front::visit::FnKind;
6
7 use rustc::lint::*;
8 use rustc::middle::def::Def::{DefVariant, DefStruct};
9
10 use utils::{in_external_macro, snippet, span_lint, span_note_and_lint};
11
12 declare_lint!(pub SHADOW_SAME, Allow,
13     "rebinding a name to itself, e.g. `let mut x = &mut x`");
14 declare_lint!(pub SHADOW_REUSE, Allow,
15     "rebinding a name to an expression that re-uses the original value, e.g. \
16     `let x = x + 1`");
17 declare_lint!(pub SHADOW_UNRELATED, Allow,
18     "The name is re-bound without even using the original value");
19
20 #[derive(Copy, Clone)]
21 pub struct ShadowPass;
22
23 impl LintPass for ShadowPass {
24     fn get_lints(&self) -> LintArray {
25         lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
26     }
27
28 }
29
30 impl LateLintPass for ShadowPass {
31     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl,
32             block: &Block, _: Span, _: NodeId) {
33         if in_external_macro(cx, block.span) { return; }
34         check_fn(cx, decl, block);
35     }
36 }
37
38 fn check_fn(cx: &LateContext, decl: &FnDecl, block: &Block) {
39     let mut bindings = Vec::new();
40     for arg in &decl.inputs {
41         if let PatIdent(_, ident, _) = arg.pat.node {
42             bindings.push((ident.node.name, ident.span))
43         }
44     }
45     check_block(cx, block, &mut bindings);
46 }
47
48 fn check_block(cx: &LateContext, block: &Block, bindings: &mut Vec<(Name, Span)>) {
49     let len = bindings.len();
50     for stmt in &block.stmts {
51         match stmt.node {
52             StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
53             StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
54                 check_expr(cx, e, bindings)
55         }
56     }
57     if let Some(ref o) = block.expr { check_expr(cx, o, bindings); }
58     bindings.truncate(len);
59 }
60
61 fn check_decl(cx: &LateContext, decl: &Decl, bindings: &mut Vec<(Name, Span)>) {
62     if in_external_macro(cx, decl.span) { return; }
63     if let DeclLocal(ref local) = decl.node {
64         let Local{ ref pat, ref ty, ref init, id: _, span } = **local;
65         if let &Some(ref t) = ty { check_ty(cx, t, bindings) }
66         if let &Some(ref o) = init {
67             check_expr(cx, o, bindings);
68             check_pat(cx, pat, &Some(o), span, bindings);
69         } else {
70             check_pat(cx, pat, &None, span, bindings);
71         }
72     }
73 }
74
75 fn is_binding(cx: &LateContext, pat: &Pat) -> bool {
76     match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
77         Some(DefVariant(..)) | Some(DefStruct(..)) => false,
78         _ => true
79     }
80 }
81
82 fn check_pat(cx: &LateContext, pat: &Pat, init: &Option<&Expr>, span: Span,
83         bindings: &mut Vec<(Name, Span)>) {
84     //TODO: match more stuff / destructuring
85     match pat.node {
86         PatIdent(_, ref ident, ref inner) => {
87             let name = ident.node.name;
88             if is_binding(cx, pat) {
89                 let mut new_binding = true;
90                 for tup in bindings.iter_mut() {
91                     if tup.0 == name {
92                         lint_shadow(cx, name, span, pat.span, init, tup.1);
93                         tup.1 = ident.span;
94                         new_binding = false;
95                         break;
96                     }
97                 }
98                 if new_binding {
99                     bindings.push((name, ident.span));
100                 }
101             }
102             if let Some(ref p) = *inner { check_pat(cx, p, init, span, bindings); }
103         },
104         //PatEnum(Path, Option<Vec<P<Pat>>>),
105         PatStruct(_, ref pfields, _) =>
106             if let Some(ref init_struct) = *init {
107                 if let ExprStruct(_, ref efields, _) = init_struct.node {
108                     for field in pfields {
109                         let name = field.node.name;
110                         let efield = efields.iter()
111                             .find(|ref f| f.name.node == name)
112                             .map(|f| &*f.expr);
113                         check_pat(cx, &field.node.pat, &efield, span, bindings);
114                     }
115                 } else {
116                     for field in pfields {
117                         check_pat(cx, &field.node.pat, init, span, bindings);
118                     }
119                 }
120             } else {
121                 for field in pfields {
122                     check_pat(cx, &field.node.pat, &None, span, bindings);
123                 }
124             },
125         PatTup(ref inner) =>
126             if let Some(ref init_tup) = *init {
127                 if let ExprTup(ref tup) = init_tup.node {
128                     for (i, p) in inner.iter().enumerate() {
129                         check_pat(cx, p, &Some(&tup[i]), p.span, bindings);
130                     }
131                 } else {
132                     for p in inner {
133                         check_pat(cx, p, init, span, bindings);
134                     }
135                 }
136             } else {
137                 for p in inner {
138                     check_pat(cx, p, &None, span, bindings);
139                 }
140             },
141         PatBox(ref inner) => {
142             if let Some(ref initp) = *init {
143                 if let ExprBox(_, ref inner_init) = initp.node {
144                     check_pat(cx, inner, &Some(&**inner_init), span, bindings);
145                 } else {
146                     check_pat(cx, inner, init, span, bindings);
147                 }
148             } else {
149                 check_pat(cx, inner, init, span, bindings);
150             }
151         },
152         PatRegion(ref inner, _) =>
153             check_pat(cx, inner, init, span, bindings),
154         //PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
155         _ => (),
156     }
157 }
158
159 fn lint_shadow<T>(cx: &LateContext, name: Name, span: Span, lspan: Span, init:
160         &Option<T>, prev_span: Span) where T: Deref<Target=Expr> {
161     fn note_orig(cx: &LateContext, lint: &'static Lint, span: Span) {
162         if cx.current_level(lint) != Level::Allow {
163             cx.sess().span_note(span, "previous binding is here");
164         }
165     }
166     if let Some(ref expr) = *init {
167         if is_self_shadow(name, expr) {
168             span_lint(cx, SHADOW_SAME, span, &format!(
169                 "{} is shadowed by itself in {}",
170                 snippet(cx, lspan, "_"),
171                 snippet(cx, expr.span, "..")));
172                 note_orig(cx, SHADOW_SAME, prev_span);
173         } else {
174             if contains_self(name, expr) {
175                 span_note_and_lint(cx, SHADOW_REUSE, lspan, &format!(
176                     "{} is shadowed by {} which reuses the original value",
177                     snippet(cx, lspan, "_"),
178                     snippet(cx, expr.span, "..")),
179                     expr.span, "initialization happens here");
180                 note_orig(cx, SHADOW_REUSE, prev_span);
181             } else {
182                 span_note_and_lint(cx, SHADOW_UNRELATED, lspan, &format!(
183                     "{} is shadowed by {}",
184                     snippet(cx, lspan, "_"),
185                     snippet(cx, expr.span, "..")),
186                     expr.span, "initialization happens here");
187                 note_orig(cx, SHADOW_UNRELATED, prev_span);
188             }
189         }
190     } else {
191         span_lint(cx, SHADOW_UNRELATED, span, &format!(
192             "{} shadows a previous declaration", snippet(cx, lspan, "_")));
193         note_orig(cx, SHADOW_UNRELATED, prev_span);
194     }
195 }
196
197 fn check_expr(cx: &LateContext, expr: &Expr, bindings: &mut Vec<(Name, Span)>) {
198     if in_external_macro(cx, expr.span) { return; }
199     match expr.node {
200         ExprUnary(_, ref e) | ExprField(ref e, _) |
201         ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(None, ref e)
202             => { check_expr(cx, e, bindings) },
203         ExprBox(Some(ref place), ref e) => {
204             check_expr(cx, place, bindings); check_expr(cx, e, bindings) }
205         ExprBlock(ref block) | ExprLoop(ref block, _) =>
206             { check_block(cx, block, bindings) },
207         //ExprCall
208         //ExprMethodCall
209         ExprVec(ref v) | ExprTup(ref v) =>
210             for ref e in v { check_expr(cx, e, bindings) },
211         ExprIf(ref cond, ref then, ref otherwise) => {
212             check_expr(cx, cond, bindings);
213             check_block(cx, then, bindings);
214             if let &Some(ref o) = otherwise { check_expr(cx, o, bindings); }
215         },
216         ExprWhile(ref cond, ref block, _) => {
217             check_expr(cx, cond, bindings);
218             check_block(cx, block, bindings);
219         },
220         ExprMatch(ref init, ref arms, _) => {
221             check_expr(cx, init, bindings);
222             let len = bindings.len();
223             for ref arm in arms {
224                 for ref pat in &arm.pats {
225                     check_pat(cx, &pat, &Some(&**init), pat.span, bindings);
226                     //This is ugly, but needed to get the right type
227                     if let Some(ref guard) = arm.guard {
228                         check_expr(cx, guard, bindings);
229                     }
230                     check_expr(cx, &arm.body, bindings);
231                     bindings.truncate(len);
232                 }
233             }
234         },
235         _ => ()
236     }
237 }
238
239 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
240     match ty.node {
241         TyParen(ref sty) | TyObjectSum(ref sty, _) |
242         TyVec(ref sty) => check_ty(cx, sty, bindings),
243         TyFixedLengthVec(ref fty, ref expr) => {
244             check_ty(cx, fty, bindings);
245             check_expr(cx, expr, bindings);
246         },
247         TyPtr(MutTy{ ty: ref mty, .. }) |
248         TyRptr(_, MutTy{ ty: ref mty, .. }) => check_ty(cx, mty, bindings),
249         TyTup(ref tup) => { for ref t in tup { check_ty(cx, t, bindings) } },
250         TyTypeof(ref expr) => check_expr(cx, expr, bindings),
251         _ => (),
252     }
253 }
254
255 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
256     match expr.node {
257         ExprBox(_, ref inner) |
258         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
259         ExprBlock(ref block) => block.stmts.is_empty() && block.expr.as_ref().
260             map_or(false, |ref e| is_self_shadow(name, e)),
261         ExprUnary(op, ref inner) => (UnUniq == op || UnDeref == op) &&
262             is_self_shadow(name, inner),
263         ExprPath(_, ref path) => path_eq_name(name, path),
264         _ => false,
265     }
266 }
267
268 fn path_eq_name(name: Name, path: &Path) -> bool {
269     !path.global && path.segments.len() == 1 &&
270         path.segments[0].identifier.name == name
271 }
272
273 fn contains_self(name: Name, expr: &Expr) -> bool {
274     match expr.node {
275         // the "self" name itself (maybe)
276         ExprPath(_, ref path) => path_eq_name(name, path),
277         // no subexprs
278         ExprLit(_) => false,
279         // one subexpr
280         ExprUnary(_, ref e) | ExprField(ref e, _) |
281         ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(_, ref e) |
282         ExprCast(ref e, _) =>
283             contains_self(name, e),
284         // two subexprs
285         ExprBinary(_, ref l, ref r) | ExprIndex(ref l, ref r) |
286         ExprAssign(ref l, ref r) | ExprAssignOp(_, ref l, ref r) |
287         ExprRepeat(ref l, ref r) =>
288             contains_self(name, l) || contains_self(name, r),
289         // one optional subexpr
290         ExprRet(ref oe) =>
291             oe.as_ref().map_or(false, |ref e| contains_self(name, e)),
292         // two optional subexprs
293         ExprRange(ref ol, ref or) =>
294             ol.as_ref().map_or(false, |ref e| contains_self(name, e)) ||
295             or.as_ref().map_or(false, |ref e| contains_self(name, e)),
296         // one subblock
297         ExprBlock(ref block) | ExprLoop(ref block, _) |
298         ExprClosure(_, _, ref block) =>
299             contains_block_self(name, block),
300         // one vec
301         ExprMethodCall(_, _, ref v) | ExprVec(ref v) | ExprTup(ref v) =>
302             v.iter().any(|ref a| contains_self(name, a)),
303         // one expr, one vec
304         ExprCall(ref fun, ref args) =>
305             contains_self(name, fun) ||
306             args.iter().any(|ref a| contains_self(name, a)),
307         // special ones
308         ExprIf(ref cond, ref then, ref otherwise) =>
309             contains_self(name, cond) || contains_block_self(name, then) ||
310             otherwise.as_ref().map_or(false, |ref e| contains_self(name, e)),
311         ExprWhile(ref e, ref block, _)  =>
312             contains_self(name, e) || contains_block_self(name, block),
313         ExprMatch(ref e, ref arms, _) =>
314             contains_self(name, e) ||
315             arms.iter().any(
316                 |ref arm|
317                 arm.pats.iter().any(|ref pat| contains_pat_self(name, pat)) ||
318                 arm.guard.as_ref().map_or(false, |ref g| contains_self(name, g)) ||
319                 contains_self(name, &arm.body)),
320         ExprStruct(_, ref fields, ref other) =>
321             fields.iter().any(|ref f| contains_self(name, &f.expr)) ||
322             other.as_ref().map_or(false, |ref e| contains_self(name, e)),
323         _ => false,
324     }
325 }
326
327 fn contains_block_self(name: Name, block: &Block) -> bool {
328     for stmt in &block.stmts {
329         match stmt.node {
330             StmtDecl(ref decl, _) =>
331             if let DeclLocal(ref local) = decl.node {
332                 //TODO: We don't currently handle the case where the name
333                 //is shadowed wiithin the block; this means code including this
334                 //degenerate pattern will get the wrong warning.
335                 if let Some(ref init) = local.init {
336                     if contains_self(name, init) { return true; }
337                 }
338             },
339             StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
340                 if contains_self(name, e) { return true }
341         }
342     }
343     if let Some(ref e) = block.expr { contains_self(name, e) } else { false }
344 }
345
346 fn contains_pat_self(name: Name, pat: &Pat) -> bool {
347     match pat.node {
348         PatIdent(_, ref ident, ref inner) => name == ident.node.name ||
349             inner.as_ref().map_or(false, |ref p| contains_pat_self(name, p)),
350         PatEnum(_, ref opats) => opats.as_ref().map_or(false,
351             |pats| pats.iter().any(|p| contains_pat_self(name, p))),
352         PatQPath(_, ref path) => path_eq_name(name, path),
353         PatStruct(_, ref fieldpats, _) => fieldpats.iter().any(
354             |ref fp| contains_pat_self(name, &fp.node.pat)),
355         PatTup(ref ps) => ps.iter().any(|ref p| contains_pat_self(name, p)),
356         PatBox(ref p) |
357         PatRegion(ref p, _) => contains_pat_self(name, p),
358         PatRange(ref from, ref until) =>
359             contains_self(name, from) || contains_self(name, until),
360         PatVec(ref pre, ref opt, ref post) =>
361             pre.iter().any(|ref p| contains_pat_self(name, p)) ||
362                 opt.as_ref().map_or(false, |ref p| contains_pat_self(name, p)) ||
363                 post.iter().any(|ref p| contains_pat_self(name, p)),
364         _ => false,
365     }
366 }