]> git.lizzy.rs Git - rust.git/blob - src/shadow.rs
rustup 2015-09-24
[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(ref e)
202             => { check_expr(cx, e, bindings) },
203         ExprBlock(ref block) | ExprLoop(ref block, _) =>
204             { check_block(cx, block, bindings) },
205         //ExprCall
206         //ExprMethodCall
207         ExprVec(ref v) | ExprTup(ref v) =>
208             for ref e in v { check_expr(cx, e, bindings) },
209         ExprIf(ref cond, ref then, ref otherwise) => {
210             check_expr(cx, cond, bindings);
211             check_block(cx, then, bindings);
212             if let &Some(ref o) = otherwise { check_expr(cx, o, bindings); }
213         },
214         ExprWhile(ref cond, ref block, _) => {
215             check_expr(cx, cond, bindings);
216             check_block(cx, block, bindings);
217         },
218         ExprMatch(ref init, ref arms, _) => {
219             check_expr(cx, init, bindings);
220             let len = bindings.len();
221             for ref arm in arms {
222                 for ref pat in &arm.pats {
223                     check_pat(cx, &pat, &Some(&**init), pat.span, bindings);
224                     //This is ugly, but needed to get the right type
225                     if let Some(ref guard) = arm.guard {
226                         check_expr(cx, guard, bindings);
227                     }
228                     check_expr(cx, &arm.body, bindings);
229                     bindings.truncate(len);
230                 }
231             }
232         },
233         _ => ()
234     }
235 }
236
237 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
238     match ty.node {
239         TyParen(ref sty) | TyObjectSum(ref sty, _) |
240         TyVec(ref sty) => check_ty(cx, sty, bindings),
241         TyFixedLengthVec(ref fty, ref expr) => {
242             check_ty(cx, fty, bindings);
243             check_expr(cx, expr, bindings);
244         },
245         TyPtr(MutTy{ ty: ref mty, .. }) |
246         TyRptr(_, MutTy{ ty: ref mty, .. }) => check_ty(cx, mty, bindings),
247         TyTup(ref tup) => { for ref t in tup { check_ty(cx, t, bindings) } },
248         TyTypeof(ref expr) => check_expr(cx, expr, bindings),
249         _ => (),
250     }
251 }
252
253 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
254     match expr.node {
255         ExprBox(ref inner) |
256         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
257         ExprBlock(ref block) => block.stmts.is_empty() && block.expr.as_ref().
258             map_or(false, |ref e| is_self_shadow(name, e)),
259         ExprUnary(op, ref inner) => (UnDeref == op) &&
260             is_self_shadow(name, inner),
261         ExprPath(_, ref path) => path_eq_name(name, path),
262         _ => false,
263     }
264 }
265
266 fn path_eq_name(name: Name, path: &Path) -> bool {
267     !path.global && path.segments.len() == 1 &&
268         path.segments[0].identifier.name == name
269 }
270
271 fn contains_self(name: Name, expr: &Expr) -> bool {
272     match expr.node {
273         // the "self" name itself (maybe)
274         ExprPath(_, ref path) => path_eq_name(name, path),
275         // no subexprs
276         ExprLit(_) => false,
277         // one subexpr
278         ExprUnary(_, ref e) | ExprField(ref e, _) |
279         ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) |
280         ExprCast(ref e, _) =>
281             contains_self(name, e),
282         // two subexprs
283         ExprBinary(_, ref l, ref r) | ExprIndex(ref l, ref r) |
284         ExprAssign(ref l, ref r) | ExprAssignOp(_, ref l, ref r) |
285         ExprRepeat(ref l, ref r) =>
286             contains_self(name, l) || contains_self(name, r),
287         // one optional subexpr
288         ExprRet(ref oe) =>
289             oe.as_ref().map_or(false, |ref e| contains_self(name, e)),
290         // two optional subexprs
291         ExprRange(ref ol, ref or) =>
292             ol.as_ref().map_or(false, |ref e| contains_self(name, e)) ||
293             or.as_ref().map_or(false, |ref e| contains_self(name, e)),
294         // one subblock
295         ExprBlock(ref block) | ExprLoop(ref block, _) |
296         ExprClosure(_, _, ref block) =>
297             contains_block_self(name, block),
298         // one vec
299         ExprMethodCall(_, _, ref v) | ExprVec(ref v) | ExprTup(ref v) =>
300             v.iter().any(|ref a| contains_self(name, a)),
301         // one expr, one vec
302         ExprCall(ref fun, ref args) =>
303             contains_self(name, fun) ||
304             args.iter().any(|ref a| contains_self(name, a)),
305         // special ones
306         ExprIf(ref cond, ref then, ref otherwise) =>
307             contains_self(name, cond) || contains_block_self(name, then) ||
308             otherwise.as_ref().map_or(false, |ref e| contains_self(name, e)),
309         ExprWhile(ref e, ref block, _)  =>
310             contains_self(name, e) || contains_block_self(name, block),
311         ExprMatch(ref e, ref arms, _) =>
312             contains_self(name, e) ||
313             arms.iter().any(
314                 |ref arm|
315                 arm.pats.iter().any(|ref pat| contains_pat_self(name, pat)) ||
316                 arm.guard.as_ref().map_or(false, |ref g| contains_self(name, g)) ||
317                 contains_self(name, &arm.body)),
318         ExprStruct(_, ref fields, ref other) =>
319             fields.iter().any(|ref f| contains_self(name, &f.expr)) ||
320             other.as_ref().map_or(false, |ref e| contains_self(name, e)),
321         _ => false,
322     }
323 }
324
325 fn contains_block_self(name: Name, block: &Block) -> bool {
326     for stmt in &block.stmts {
327         match stmt.node {
328             StmtDecl(ref decl, _) =>
329             if let DeclLocal(ref local) = decl.node {
330                 //TODO: We don't currently handle the case where the name
331                 //is shadowed wiithin the block; this means code including this
332                 //degenerate pattern will get the wrong warning.
333                 if let Some(ref init) = local.init {
334                     if contains_self(name, init) { return true; }
335                 }
336             },
337             StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
338                 if contains_self(name, e) { return true }
339         }
340     }
341     if let Some(ref e) = block.expr { contains_self(name, e) } else { false }
342 }
343
344 fn contains_pat_self(name: Name, pat: &Pat) -> bool {
345     match pat.node {
346         PatIdent(_, ref ident, ref inner) => name == ident.node.name ||
347             inner.as_ref().map_or(false, |ref p| contains_pat_self(name, p)),
348         PatEnum(_, ref opats) => opats.as_ref().map_or(false,
349             |pats| pats.iter().any(|p| contains_pat_self(name, p))),
350         PatQPath(_, ref path) => path_eq_name(name, path),
351         PatStruct(_, ref fieldpats, _) => fieldpats.iter().any(
352             |ref fp| contains_pat_self(name, &fp.node.pat)),
353         PatTup(ref ps) => ps.iter().any(|ref p| contains_pat_self(name, p)),
354         PatBox(ref p) |
355         PatRegion(ref p, _) => contains_pat_self(name, p),
356         PatRange(ref from, ref until) =>
357             contains_self(name, from) || contains_self(name, until),
358         PatVec(ref pre, ref opt, ref post) =>
359             pre.iter().any(|ref p| contains_pat_self(name, p)) ||
360                 opt.as_ref().map_or(false, |ref p| contains_pat_self(name, p)) ||
361                 post.iter().any(|ref p| contains_pat_self(name, p)),
362         _ => false,
363     }
364 }