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(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) },
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); }
216 ExprWhile(ref cond, ref block, _) => {
217 check_expr(cx, cond, bindings);
218 check_block(cx, block, bindings);
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);
230 check_expr(cx, &arm.body, bindings);
231 bindings.truncate(len);
239 fn check_ty(cx: &LateContext, ty: &Ty, bindings: &mut Vec<(Name, Span)>) {
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);
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),
255 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
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),
268 fn path_eq_name(name: Name, path: &Path) -> bool {
269 !path.global && path.segments.len() == 1 &&
270 path.segments[0].identifier.name == name
273 fn contains_self(name: Name, expr: &Expr) -> bool {
275 // the "self" name itself (maybe)
276 ExprPath(_, ref path) => path_eq_name(name, path),
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),
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
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)),
297 ExprBlock(ref block) | ExprLoop(ref block, _) |
298 ExprClosure(_, _, ref block) =>
299 contains_block_self(name, block),
301 ExprMethodCall(_, _, ref v) | ExprVec(ref v) | ExprTup(ref v) =>
302 v.iter().any(|ref a| contains_self(name, a)),
304 ExprCall(ref fun, ref args) =>
305 contains_self(name, fun) ||
306 args.iter().any(|ref a| contains_self(name, a)),
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) ||
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)),
327 fn contains_block_self(name: Name, block: &Block) -> bool {
328 for stmt in &block.stmts {
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; }
339 StmtExpr(ref e, _) | StmtSemi(ref e, _) =>
340 if contains_self(name, e) { return true }
343 if let Some(ref e) = block.expr { contains_self(name, e) } else { false }
346 fn contains_pat_self(name: Name, pat: &Pat) -> bool {
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)),
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)),