2 use rustc_front::hir::*;
4 use syntax::codemap::Span;
5 use rustc_front::visit::FnKind;
8 use rustc::middle::def::Def::{DefVariant, DefStruct};
10 use utils::{in_external_macro, snippet, span_lint, span_note_and_lint};
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. \
17 declare_lint!(pub SHADOW_UNRELATED, Allow,
18 "The name is re-bound without even using the original value");
20 #[derive(Copy, Clone)]
21 pub struct ShadowPass;
23 impl LintPass for ShadowPass {
24 fn get_lints(&self) -> LintArray {
25 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
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);
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))
45 check_block(cx, block, &mut bindings);
48 fn check_block(cx: &LateContext, block: &Block, bindings: &mut Vec<(Name, Span)>) {
49 let len = bindings.len();
50 for stmt in &block.stmts {
52 StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
53 StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
54 check_expr(cx, e, bindings)
57 if let Some(ref o) = block.expr { check_expr(cx, o, bindings); }
58 bindings.truncate(len);
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);
70 check_pat(cx, pat, &None, span, bindings);
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,
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
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() {
92 lint_shadow(cx, name, span, pat.span, init, tup.1);
99 bindings.push((name, ident.span));
102 if let Some(ref p) = *inner { check_pat(cx, p, init, span, bindings); }
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)
113 check_pat(cx, &field.node.pat, &efield, span, bindings);
116 for field in pfields {
117 check_pat(cx, &field.node.pat, init, span, bindings);
121 for field in pfields {
122 check_pat(cx, &field.node.pat, &None, span, bindings);
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);
133 check_pat(cx, p, init, span, bindings);
138 check_pat(cx, p, &None, span, bindings);
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);
146 check_pat(cx, inner, init, span, bindings);
149 check_pat(cx, inner, init, span, bindings);
152 PatRegion(ref inner, _) =>
153 check_pat(cx, inner, init, span, bindings),
154 //PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
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");
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);
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);
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);
191 span_lint(cx, SHADOW_UNRELATED, span, &format!(
192 "{} shadows a previous declaration", snippet(cx, lspan, "_")));
193 note_orig(cx, SHADOW_UNRELATED, prev_span);
197 fn check_expr(cx: &LateContext, expr: &Expr, bindings: &mut Vec<(Name, Span)>) {
198 if in_external_macro(cx, expr.span) { return; }
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) },
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); }
214 ExprWhile(ref cond, ref block, _) => {
215 check_expr(cx, cond, bindings);
216 check_block(cx, block, bindings);
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);
228 check_expr(cx, &arm.body, bindings);
229 bindings.truncate(len);
237 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
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);
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),
253 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
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),
266 fn path_eq_name(name: Name, path: &Path) -> bool {
267 !path.global && path.segments.len() == 1 &&
268 path.segments[0].identifier.name == name
271 fn contains_self(name: Name, expr: &Expr) -> bool {
273 // the "self" name itself (maybe)
274 ExprPath(_, ref path) => path_eq_name(name, path),
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),
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
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)),
295 ExprBlock(ref block) | ExprLoop(ref block, _) |
296 ExprClosure(_, _, ref block) =>
297 contains_block_self(name, block),
299 ExprMethodCall(_, _, ref v) | ExprVec(ref v) | ExprTup(ref v) =>
300 v.iter().any(|ref a| contains_self(name, a)),
302 ExprCall(ref fun, ref args) =>
303 contains_self(name, fun) ||
304 args.iter().any(|ref a| contains_self(name, a)),
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) ||
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)),
325 fn contains_block_self(name: Name, block: &Block) -> bool {
326 for stmt in &block.stmts {
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; }
337 StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
338 if contains_self(name, e) { return true }
341 if let Some(ref e) = block.expr { contains_self(name, e) } else { false }
344 fn contains_pat_self(name: Name, pat: &Pat) -> bool {
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)),
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)),