4 use rustc::hir::intravisit::{Visitor, FnKind, NestedVisitorMap};
6 use syntax::codemap::Span;
7 use utils::{higher, in_external_macro, snippet, span_lint_and_then, iter_input_pats};
9 /// **What it does:** Checks for bindings that shadow other bindings already in
10 /// scope, while just changing reference level or mutability.
12 /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
13 /// code. Still, some may opt to avoid it in their code base, they can set this
16 /// **Known problems:** This lint, as the other shadowing related lints,
17 /// currently only catches very simple patterns.
26 "rebinding a name to itself, e.g. `let mut x = &mut x`"
29 /// **What it does:** Checks for bindings that shadow other bindings already in
30 /// scope, while reusing the original value.
32 /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
33 /// code. Still, some argue that name shadowing like this hurts readability,
34 /// because a value may be bound to different things depending on position in
37 /// **Known problems:** This lint, as the other shadowing related lints,
38 /// currently only catches very simple patterns.
47 "rebinding a name to an expression that re-uses the original value, e.g. \
51 /// **What it does:** Checks for bindings that shadow other bindings already in
52 /// scope, either without a initialization or with one that does not even use
53 /// the original value.
55 /// **Why is this bad?** Name shadowing can hurt readability, especially in
56 /// large code bases, because it is easy to lose track of the active binding at
57 /// any place in the code. This can be alleviated by either giving more specific
58 /// names to bindings ore introducing more scopes to contain the bindings.
60 /// **Known problems:** This lint, as the other shadowing related lints,
61 /// currently only catches very simple patterns.
65 /// let x = y; let x = z; // shadows the earlier binding
70 "rebinding a name without even using the original value"
73 #[derive(Copy, Clone)]
76 impl LintPass for Pass {
77 fn get_lints(&self) -> LintArray {
78 lint_array!(SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED)
82 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
85 cx: &LateContext<'a, 'tcx>,
92 if in_external_macro(cx, body.value.span) {
95 check_fn(cx, decl, body);
99 fn check_fn<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, body: &'tcx Body) {
100 let mut bindings = Vec::new();
101 for arg in iter_input_pats(decl, body) {
102 if let PatKind::Binding(_, _, ident, _) = arg.pat.node {
103 bindings.push((ident.node, ident.span))
106 check_expr(cx, &body.value, &mut bindings);
109 fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, bindings: &mut Vec<(Name, Span)>) {
110 let len = bindings.len();
111 for stmt in &block.stmts {
113 StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
115 StmtSemi(ref e, _) => check_expr(cx, e, bindings),
118 if let Some(ref o) = block.expr {
119 check_expr(cx, o, bindings);
121 bindings.truncate(len);
124 fn check_decl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl, bindings: &mut Vec<(Name, Span)>) {
125 if in_external_macro(cx, decl.span) {
128 if higher::is_from_for_desugar(decl) {
131 if let DeclLocal(ref local) = decl.node {
132 let Local { ref pat, ref ty, ref init, span, .. } = **local;
133 if let Some(ref t) = *ty {
134 check_ty(cx, t, bindings)
136 if let Some(ref o) = *init {
137 check_expr(cx, o, bindings);
138 check_pat(cx, pat, Some(o), span, bindings);
140 check_pat(cx, pat, None, span, bindings);
145 fn is_binding(cx: &LateContext, pat_id: NodeId) -> bool {
146 let var_ty = cx.tables.node_id_to_type(pat_id);
148 ty::TyAdt(..) => false,
153 fn check_pat<'a, 'tcx>(
154 cx: &LateContext<'a, 'tcx>,
156 init: Option<&'tcx Expr>,
158 bindings: &mut Vec<(Name, Span)>
160 // TODO: match more stuff / destructuring
162 PatKind::Binding(_, _, ref ident, ref inner) => {
163 let name = ident.node;
164 if is_binding(cx, pat.id) {
165 let mut new_binding = true;
166 for tup in bindings.iter_mut() {
168 lint_shadow(cx, name, span, pat.span, init, tup.1);
175 bindings.push((name, ident.span));
178 if let Some(ref p) = *inner {
179 check_pat(cx, p, init, span, bindings);
182 PatKind::Struct(_, ref pfields, _) => {
183 if let Some(init_struct) = init {
184 if let ExprStruct(_, ref efields, _) = init_struct.node {
185 for field in pfields {
186 let name = field.node.name;
187 let efield = efields.iter()
188 .find(|f| f.name.node == name)
190 check_pat(cx, &field.node.pat, efield, span, bindings);
193 for field in pfields {
194 check_pat(cx, &field.node.pat, init, span, bindings);
198 for field in pfields {
199 check_pat(cx, &field.node.pat, None, span, bindings);
203 PatKind::Tuple(ref inner, _) => {
204 if let Some(init_tup) = init {
205 if let ExprTup(ref tup) = init_tup.node {
206 for (i, p) in inner.iter().enumerate() {
207 check_pat(cx, p, Some(&tup[i]), p.span, bindings);
211 check_pat(cx, p, init, span, bindings);
216 check_pat(cx, p, None, span, bindings);
220 PatKind::Box(ref inner) => {
221 if let Some(initp) = init {
222 if let ExprBox(ref inner_init) = initp.node {
223 check_pat(cx, inner, Some(&**inner_init), span, bindings);
225 check_pat(cx, inner, init, span, bindings);
228 check_pat(cx, inner, init, span, bindings);
231 PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
232 // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
237 fn lint_shadow<'a, 'tcx: 'a>(
238 cx: &LateContext<'a, 'tcx>,
242 init: Option<&'tcx Expr>,
245 if let Some(expr) = init {
246 if is_self_shadow(name, expr) {
247 span_lint_and_then(cx,
250 &format!("`{}` is shadowed by itself in `{}`",
251 snippet(cx, pattern_span, "_"),
252 snippet(cx, expr.span, "..")),
253 |db| { db.span_note(prev_span, "previous binding is here"); });
254 } else if contains_self(cx, name, expr) {
255 span_lint_and_then(cx,
258 &format!("`{}` is shadowed by `{}` which reuses the original value",
259 snippet(cx, pattern_span, "_"),
260 snippet(cx, expr.span, "..")),
262 db.span_note(expr.span, "initialization happens here");
263 db.span_note(prev_span, "previous binding is here");
266 span_lint_and_then(cx,
269 &format!("`{}` is shadowed by `{}`",
270 snippet(cx, pattern_span, "_"),
271 snippet(cx, expr.span, "..")),
273 db.span_note(expr.span, "initialization happens here");
274 db.span_note(prev_span, "previous binding is here");
279 span_lint_and_then(cx,
282 &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
283 |db| { db.span_note(prev_span, "previous binding is here"); });
287 fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) {
288 if in_external_macro(cx, expr.span) {
292 ExprUnary(_, ref e) |
293 ExprField(ref e, _) |
294 ExprTupField(ref e, _) |
295 ExprAddrOf(_, ref e) |
296 ExprBox(ref e) => check_expr(cx, e, bindings),
297 ExprBlock(ref block) |
298 ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
301 ExprArray(ref v) | ExprTup(ref v) => {
303 check_expr(cx, e, bindings)
306 ExprIf(ref cond, ref then, ref otherwise) => {
307 check_expr(cx, cond, bindings);
308 check_block(cx, then, bindings);
309 if let Some(ref o) = *otherwise {
310 check_expr(cx, o, bindings);
313 ExprWhile(ref cond, ref block, _) => {
314 check_expr(cx, cond, bindings);
315 check_block(cx, block, bindings);
317 ExprMatch(ref init, ref arms, _) => {
318 check_expr(cx, init, bindings);
319 let len = bindings.len();
321 for pat in &arm.pats {
322 check_pat(cx, pat, Some(&**init), pat.span, bindings);
323 // This is ugly, but needed to get the right type
324 if let Some(ref guard) = arm.guard {
325 check_expr(cx, guard, bindings);
327 check_expr(cx, &arm.body, bindings);
328 bindings.truncate(len);
336 fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut Vec<(Name, Span)>) {
338 TyObjectSum(ref sty, _) |
339 TySlice(ref sty) => check_ty(cx, sty, bindings),
340 TyArray(ref fty, body_id) => {
341 check_ty(cx, fty, bindings);
342 check_expr(cx, &cx.tcx.map.body(body_id).value, bindings);
344 TyPtr(MutTy { ty: ref mty, .. }) |
345 TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
348 check_ty(cx, t, bindings)
351 TyTypeof(body_id) => check_expr(cx, &cx.tcx.map.body(body_id).value, bindings),
356 fn is_self_shadow(name: Name, expr: &Expr) -> bool {
359 ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
360 ExprBlock(ref block) => {
361 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
363 ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
364 ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
369 fn path_eq_name(name: Name, path: &Path) -> bool {
370 !path.is_global() && path.segments.len() == 1 && path.segments[0].name.as_str() == name.as_str()
373 struct ContainsSelf<'a, 'tcx: 'a> {
376 cx: &'a LateContext<'a, 'tcx>,
379 impl<'a, 'tcx: 'a> Visitor<'tcx> for ContainsSelf<'a, 'tcx> {
380 fn visit_name(&mut self, _: Span, name: Name) {
381 if self.name == name {
385 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
386 NestedVisitorMap::All(&self.cx.tcx.map)
390 fn contains_self<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, name: Name, expr: &'tcx Expr) -> bool {
391 let mut cs = ContainsSelf {