]> git.lizzy.rs Git - rust.git/blob - src/shadow.rs
fb840fd32581eebb29d6b84bb6a15e2c1ade613b
[rust.git] / src / shadow.rs
1 use std::ops::Deref;
2 use syntax::ast::*;
3 use syntax::codemap::Span;
4 use syntax::visit::FnKind;
5
6 use rustc::lint::{Context, LintArray, LintPass};
7 use rustc::middle::def::Def::{DefVariant, DefStruct};
8
9 use utils::{in_external_macro, snippet, span_lint};
10
11 declare_lint!(pub SHADOW_SAME, Allow,
12     "rebinding a name to itself, e.g. `let mut x = &mut x`");
13 declare_lint!(pub SHADOW_REUSE, Allow,
14     "rebinding a name to an expression that re-uses the original value, e.g. \
15     `let x = x + 1`");
16 declare_lint!(pub SHADOW_UNRELATED, Warn,
17     "The name is re-bound without even using the original value");
18
19 #[derive(Copy, Clone)]
20 pub struct ShadowPass;
21
22 impl LintPass for ShadowPass {
23     fn get_lints(&self) -> LintArray {
24         lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
25     }
26
27     fn check_fn(&mut self, cx: &Context, _: FnKind, decl: &FnDecl,
28             block: &Block, _: Span, _: NodeId) {
29         if in_external_macro(cx, block.span) { return; }
30         check_fn(cx, decl, block);
31     }
32 }
33
34 fn check_fn(cx: &Context, decl: &FnDecl, block: &Block) {
35     let mut bindings = Vec::new();
36     for arg in &decl.inputs {
37         if let PatIdent(_, ident, _) = arg.pat.node {
38             bindings.push(ident.node.name)
39         }
40     }
41     check_block(cx, block, &mut bindings);
42 }
43
44 fn check_block(cx: &Context, block: &Block, bindings: &mut Vec<Name>) {
45     let len = bindings.len();
46     for stmt in &block.stmts {
47         match stmt.node {
48             StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
49             StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
50                 check_expr(cx, e, bindings),
51             _ => ()
52         }
53     }
54     if let Some(ref o) = block.expr { check_expr(cx, o, bindings); }
55     bindings.truncate(len);
56 }
57
58 fn check_decl(cx: &Context, decl: &Decl, bindings: &mut Vec<Name>) {
59     if in_external_macro(cx, decl.span) { return; }
60     if let DeclLocal(ref local) = decl.node {
61         let Local{ ref pat, ref ty, ref init, id: _, span } = **local;
62         if let &Some(ref t) = ty { check_ty(cx, t, bindings) }
63         if let &Some(ref o) = init { check_expr(cx, o, bindings) }
64         check_pat(cx, pat, init, span, bindings);
65     }
66 }
67
68 fn is_binding(cx: &Context, pat: &Pat) -> bool {
69     match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
70         Some(DefVariant(..)) | Some(DefStruct(..)) => false,
71         _ => true
72     }
73 }
74
75 fn check_pat<T>(cx: &Context, pat: &Pat, init: &Option<T>, span: Span,  
76         bindings: &mut Vec<Name>) where T: Deref<Target=Expr> {
77     //TODO: match more stuff / destructuring
78     match pat.node {
79         PatIdent(_, ref ident, ref inner) => {
80             let name = ident.node.name;
81             if is_binding(cx, pat) {
82                 if bindings.contains(&name) {
83                     lint_shadow(cx, name, span, pat.span, init);
84                 } else {
85                     bindings.push(name);
86                 }
87             }
88             if let Some(ref p) = *inner { check_pat(cx, p, init, span, bindings); }
89         },
90         //PatEnum(Path, Option<Vec<P<Pat>>>),
91         //PatQPath(QSelf, Path),
92         //PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
93         //PatTup(Vec<P<Pat>>),
94         PatBox(ref inner) => {
95             if let Some(ref initp) = *init {
96                 match initp.node {
97                     ExprBox(_, ref inner_init) => 
98                         check_pat(cx, inner, &Some(&**inner_init), span, bindings),
99                     //TODO: ExprCall on Box::new
100                     _ => check_pat(cx, inner, init, span, bindings),
101                 }
102             } else {
103                 check_pat(cx, inner, init, span, bindings);
104             }
105         },
106         //PatRegion(P<Pat>, Mutability),
107         //PatRange(P<Expr>, P<Expr>),
108         //PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
109         _ => (),
110     }
111 }
112
113 fn lint_shadow<T>(cx: &Context, name: Name, span: Span, lspan: Span, init: 
114         &Option<T>) where T: Deref<Target=Expr> {
115     if let &Some(ref expr) = init {
116         if is_self_shadow(name, expr) {
117             span_lint(cx, SHADOW_SAME, span, &format!(
118                 "{} is shadowed by itself in {}",
119                 snippet(cx, lspan, "_"),
120                 snippet(cx, expr.span, "..")));
121         } else {
122             if contains_self(name, expr) {
123                 span_lint(cx, SHADOW_REUSE, span, &format!(
124                     "{} is shadowed by {} which reuses the original value",
125                     snippet(cx, lspan, "_"),
126                     snippet(cx, expr.span, "..")));
127             } else {
128                 span_lint(cx, SHADOW_UNRELATED, span, &format!(
129                     "{} is shadowed by {} in this declaration",
130                     snippet(cx, lspan, "_"),
131                     snippet(cx, expr.span, "..")));
132             }
133         }
134     } else {
135         span_lint(cx, SHADOW_UNRELATED, span, &format!(
136             "{} is shadowed in this declaration", snippet(cx, lspan, "_")));
137     }
138 }
139
140 fn check_expr(cx: &Context, expr: &Expr, bindings: &mut Vec<Name>) {
141     if in_external_macro(cx, expr.span) { return; }
142     match expr.node {
143         ExprUnary(_, ref e) | ExprParen(ref e) | ExprField(ref e, _) |
144         ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(None, ref e)
145             => { check_expr(cx, e, bindings) },
146         ExprBox(Some(ref place), ref e) => {
147             check_expr(cx, place, bindings); check_expr(cx, e, bindings) }
148         ExprBlock(ref block) | ExprLoop(ref block, _) =>
149             { check_block(cx, block, bindings) },
150         //ExprCall
151         //ExprMethodCall
152         ExprVec(ref v) | ExprTup(ref v) =>
153             for ref e in v { check_expr(cx, e, bindings) },
154         ExprIf(ref cond, ref then, ref otherwise) => {
155             check_expr(cx, cond, bindings);
156             check_block(cx, then, bindings);
157             if let &Some(ref o) = otherwise { check_expr(cx, o, bindings); }
158         },
159         ExprWhile(ref cond, ref block, _) => {
160             check_expr(cx, cond, bindings);
161             check_block(cx, block, bindings);
162         },
163         ExprMatch(ref init, ref arms, _) => {
164             check_expr(cx, init, bindings);
165             let len = bindings.len();
166             for ref arm in arms {
167                 for ref pat in &arm.pats {
168                     check_pat(cx, &pat, &Some(&**init), pat.span, bindings);
169                     //TODO: This is ugly, but needed to get the right type
170                 }
171                 if let Some(ref guard) = arm.guard {
172                     check_expr(cx, guard, bindings);
173                 }
174                 check_expr(cx, &arm.body, bindings);
175                 bindings.truncate(len);
176             }
177         },
178         _ => ()
179     }
180 }
181
182 fn check_ty(cx: &Context, ty: &Ty, bindings: &mut Vec<Name>) {
183     match ty.node {
184         TyParen(ref sty) | TyObjectSum(ref sty, _) |
185         TyVec(ref sty) => check_ty(cx, sty, bindings),
186         TyFixedLengthVec(ref fty, ref expr) => {
187             check_ty(cx, fty, bindings);
188             check_expr(cx, expr, bindings);
189         },
190         TyPtr(MutTy{ ty: ref mty, .. }) |
191         TyRptr(_, MutTy{ ty: ref mty, .. }) => check_ty(cx, mty, bindings),
192         TyTup(ref tup) => { for ref t in tup { check_ty(cx, t, bindings) } },
193         TyTypeof(ref expr) => check_expr(cx, expr, bindings),
194         _ => (),
195     }
196 }
197
198 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
199     match expr.node {
200         ExprBox(_, ref inner) |
201         ExprParen(ref inner) |
202         ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
203         ExprBlock(ref block) => block.stmts.is_empty() && block.expr.as_ref().
204             map_or(false, |ref e| is_self_shadow(name, e)),
205         ExprUnary(op, ref inner) => (UnUniq == op || UnDeref == op) &&
206             is_self_shadow(name, inner),
207         ExprPath(_, ref path) => path_eq_name(name, path),
208         _ => false,
209     }
210 }
211
212 fn path_eq_name(name: Name, path: &Path) -> bool {
213     !path.global && path.segments.len() == 1 && 
214         path.segments[0].identifier.name == name
215 }
216
217 fn contains_self(name: Name, expr: &Expr) -> bool {
218     match expr.node {
219         ExprUnary(_, ref e) | ExprParen(ref e) | ExprField(ref e, _) |
220         ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(_, ref e)
221             => contains_self(name, e),
222         ExprBinary(_, ref l, ref r) =>
223             contains_self(name, l) || contains_self(name, r),
224         ExprBlock(ref block) | ExprLoop(ref block, _) =>
225             contains_block_self(name, block),
226         ExprCall(ref fun, ref args) => contains_self(name, fun) ||
227             args.iter().any(|ref a| contains_self(name, a)),
228         ExprMethodCall(_, _, ref args) =>
229             args.iter().any(|ref a| contains_self(name, a)),
230         ExprVec(ref v) | ExprTup(ref v) =>
231             v.iter().any(|ref e| contains_self(name, e)),
232         ExprIf(ref cond, ref then, ref otherwise) =>
233             contains_self(name, cond) || contains_block_self(name, then) ||
234             otherwise.as_ref().map_or(false, |ref e| contains_self(name, e)),
235         ExprWhile(ref e, ref block, _)  =>
236             contains_self(name, e) || contains_block_self(name, block),
237         ExprMatch(ref e, ref arms, _) => 
238             arms.iter().any(|ref arm| arm.pats.iter().any(|ref pat| 
239                 contains_pat_self(name, pat))) || contains_self(name, e),
240         ExprPath(_, ref path) => path_eq_name(name, path),
241         _ => false
242     }
243 }
244
245 fn contains_block_self(name: Name, block: &Block) -> bool {
246     for stmt in &block.stmts {
247         match stmt.node {
248             StmtDecl(ref decl, _) =>
249             if let DeclLocal(ref local) = decl.node {
250                 //TODO: We don't currently handle the case where the name
251                 //is shadowed wiithin the block; this means code including this
252                 //degenerate pattern will get the wrong warning.
253                 if let Some(ref init) = local.init {
254                     if contains_self(name, init) { return true; }
255                 }
256             },
257             StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
258                 if contains_self(name, e) { return true },
259             _ => ()
260         }
261     }
262     if let Some(ref e) = block.expr { contains_self(name, e) } else { false }
263 }
264
265 fn contains_pat_self(name: Name, pat: &Pat) -> bool {
266     match pat.node {
267         PatIdent(_, ref ident, ref inner) => name == ident.node.name ||
268             inner.as_ref().map_or(false, |ref p| contains_pat_self(name, p)),
269         PatEnum(_, ref opats) => opats.as_ref().map_or(false, 
270             |pats| pats.iter().any(|p| contains_pat_self(name, p))),
271         PatQPath(_, ref path) => path_eq_name(name, path),
272         PatStruct(_, ref fieldpats, _) => fieldpats.iter().any(
273             |ref fp| contains_pat_self(name, &fp.node.pat)),
274         PatTup(ref ps) => ps.iter().any(|ref p| contains_pat_self(name, p)),
275         PatBox(ref p) |
276         PatRegion(ref p, _) => contains_pat_self(name, p),
277         PatRange(ref from, ref until) => 
278             contains_self(name, from) || contains_self(name, until),
279         PatVec(ref pre, ref opt, ref post) =>
280             pre.iter().any(|ref p| contains_pat_self(name, p)) || 
281                 opt.as_ref().map_or(false, |ref p| contains_pat_self(name, p)) ||
282                 post.iter().any(|ref p| contains_pat_self(name, p)),
283         _ => false,
284     }
285 }