]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/shadow.rs
Auto merge of #73490 - CAD97:range-unchecked-stepping, r=Amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / shadow.rs
1 use crate::reexport::Name;
2 use crate::utils::{contains_name, higher, iter_input_pats, snippet, span_lint_and_then};
3 use rustc_hir::intravisit::FnKind;
4 use rustc_hir::{
5     Block, Body, Expr, ExprKind, FnDecl, Guard, HirId, Local, MutTy, Pat, PatKind, Path, QPath, StmtKind, Ty, TyKind,
6     UnOp,
7 };
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for bindings that shadow other bindings already in
16     /// scope, while just changing reference level or mutability.
17     ///
18     /// **Why is this bad?** Not much, in fact it's a very common pattern in Rust
19     /// code. Still, some may opt to avoid it in their code base, they can set this
20     /// lint to `Warn`.
21     ///
22     /// **Known problems:** This lint, as the other shadowing related lints,
23     /// currently only catches very simple patterns.
24     ///
25     /// **Example:**
26     /// ```rust
27     /// # let x = 1;
28     ///
29     /// // Bad
30     /// let x = &x;
31     ///
32     /// // Good
33     /// let y = &x; // use different variable name
34     /// ```
35     pub SHADOW_SAME,
36     restriction,
37     "rebinding a name to itself, e.g., `let mut x = &mut x`"
38 }
39
40 declare_clippy_lint! {
41     /// **What it does:** Checks for bindings that shadow other bindings already in
42     /// scope, while reusing the original value.
43     ///
44     /// **Why is this bad?** Not too much, in fact it's a common pattern in Rust
45     /// code. Still, some argue that name shadowing like this hurts readability,
46     /// because a value may be bound to different things depending on position in
47     /// the code.
48     ///
49     /// **Known problems:** This lint, as the other shadowing related lints,
50     /// currently only catches very simple patterns.
51     ///
52     /// **Example:**
53     /// ```rust
54     /// let x = 2;
55     /// let x = x + 1;
56     /// ```
57     /// use different variable name:
58     /// ```rust
59     /// let x = 2;
60     /// let y = x + 1;
61     /// ```
62     pub SHADOW_REUSE,
63     restriction,
64     "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`"
65 }
66
67 declare_clippy_lint! {
68     /// **What it does:** Checks for bindings that shadow other bindings already in
69     /// scope, either without a initialization or with one that does not even use
70     /// the original value.
71     ///
72     /// **Why is this bad?** Name shadowing can hurt readability, especially in
73     /// large code bases, because it is easy to lose track of the active binding at
74     /// any place in the code. This can be alleviated by either giving more specific
75     /// names to bindings or introducing more scopes to contain the bindings.
76     ///
77     /// **Known problems:** This lint, as the other shadowing related lints,
78     /// currently only catches very simple patterns.
79     ///
80     /// **Example:**
81     /// ```rust
82     /// # let y = 1;
83     /// # let z = 2;
84     /// let x = y;
85     ///
86     /// // Bad
87     /// let x = z; // shadows the earlier binding
88     ///
89     /// // Good
90     /// let w = z; // use different variable name
91     /// ```
92     pub SHADOW_UNRELATED,
93     pedantic,
94     "rebinding a name without even using the original value"
95 }
96
97 declare_lint_pass!(Shadow => [SHADOW_SAME, SHADOW_REUSE, SHADOW_UNRELATED]);
98
99 impl<'tcx> LateLintPass<'tcx> for Shadow {
100     fn check_fn(
101         &mut self,
102         cx: &LateContext<'tcx>,
103         _: FnKind<'tcx>,
104         decl: &'tcx FnDecl<'_>,
105         body: &'tcx Body<'_>,
106         _: Span,
107         _: HirId,
108     ) {
109         if in_external_macro(cx.sess(), body.value.span) {
110             return;
111         }
112         check_fn(cx, decl, body);
113     }
114 }
115
116 fn check_fn<'tcx>(cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>) {
117     let mut bindings = Vec::with_capacity(decl.inputs.len());
118     for arg in iter_input_pats(decl, body) {
119         if let PatKind::Binding(.., ident, _) = arg.pat.kind {
120             bindings.push((ident.name, ident.span))
121         }
122     }
123     check_expr(cx, &body.value, &mut bindings);
124 }
125
126 fn check_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'_>, bindings: &mut Vec<(Name, Span)>) {
127     let len = bindings.len();
128     for stmt in block.stmts {
129         match stmt.kind {
130             StmtKind::Local(ref local) => check_local(cx, local, bindings),
131             StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => check_expr(cx, e, bindings),
132             StmtKind::Item(..) => {},
133         }
134     }
135     if let Some(ref o) = block.expr {
136         check_expr(cx, o, bindings);
137     }
138     bindings.truncate(len);
139 }
140
141 fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Name, Span)>) {
142     if in_external_macro(cx.sess(), local.span) {
143         return;
144     }
145     if higher::is_from_for_desugar(local) {
146         return;
147     }
148     let Local {
149         ref pat,
150         ref ty,
151         ref init,
152         span,
153         ..
154     } = *local;
155     if let Some(ref t) = *ty {
156         check_ty(cx, t, bindings)
157     }
158     if let Some(ref o) = *init {
159         check_expr(cx, o, bindings);
160         check_pat(cx, pat, Some(o), span, bindings);
161     } else {
162         check_pat(cx, pat, None, span, bindings);
163     }
164 }
165
166 fn is_binding(cx: &LateContext<'_>, pat_id: HirId) -> bool {
167     let var_ty = cx.tables().node_type_opt(pat_id);
168     if let Some(var_ty) = var_ty {
169         match var_ty.kind {
170             ty::Adt(..) => false,
171             _ => true,
172         }
173     } else {
174         false
175     }
176 }
177
178 fn check_pat<'tcx>(
179     cx: &LateContext<'tcx>,
180     pat: &'tcx Pat<'_>,
181     init: Option<&'tcx Expr<'_>>,
182     span: Span,
183     bindings: &mut Vec<(Name, Span)>,
184 ) {
185     // TODO: match more stuff / destructuring
186     match pat.kind {
187         PatKind::Binding(.., ident, ref inner) => {
188             let name = ident.name;
189             if is_binding(cx, pat.hir_id) {
190                 let mut new_binding = true;
191                 for tup in bindings.iter_mut() {
192                     if tup.0 == name {
193                         lint_shadow(cx, name, span, pat.span, init, tup.1);
194                         tup.1 = ident.span;
195                         new_binding = false;
196                         break;
197                     }
198                 }
199                 if new_binding {
200                     bindings.push((name, ident.span));
201                 }
202             }
203             if let Some(ref p) = *inner {
204                 check_pat(cx, p, init, span, bindings);
205             }
206         },
207         PatKind::Struct(_, pfields, _) => {
208             if let Some(init_struct) = init {
209                 if let ExprKind::Struct(_, ref efields, _) = init_struct.kind {
210                     for field in pfields {
211                         let name = field.ident.name;
212                         let efield = efields
213                             .iter()
214                             .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
215                         check_pat(cx, &field.pat, efield, span, bindings);
216                     }
217                 } else {
218                     for field in pfields {
219                         check_pat(cx, &field.pat, init, span, bindings);
220                     }
221                 }
222             } else {
223                 for field in pfields {
224                     check_pat(cx, &field.pat, None, span, bindings);
225                 }
226             }
227         },
228         PatKind::Tuple(inner, _) => {
229             if let Some(init_tup) = init {
230                 if let ExprKind::Tup(ref tup) = init_tup.kind {
231                     for (i, p) in inner.iter().enumerate() {
232                         check_pat(cx, p, Some(&tup[i]), p.span, bindings);
233                     }
234                 } else {
235                     for p in inner {
236                         check_pat(cx, p, init, span, bindings);
237                     }
238                 }
239             } else {
240                 for p in inner {
241                     check_pat(cx, p, None, span, bindings);
242                 }
243             }
244         },
245         PatKind::Box(ref inner) => {
246             if let Some(initp) = init {
247                 if let ExprKind::Box(ref inner_init) = initp.kind {
248                     check_pat(cx, inner, Some(&**inner_init), span, bindings);
249                 } else {
250                     check_pat(cx, inner, init, span, bindings);
251                 }
252             } else {
253                 check_pat(cx, inner, init, span, bindings);
254             }
255         },
256         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
257         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
258         _ => (),
259     }
260 }
261
262 fn lint_shadow<'tcx>(
263     cx: &LateContext<'tcx>,
264     name: Name,
265     span: Span,
266     pattern_span: Span,
267     init: Option<&'tcx Expr<'_>>,
268     prev_span: Span,
269 ) {
270     if let Some(expr) = init {
271         if is_self_shadow(name, expr) {
272             span_lint_and_then(
273                 cx,
274                 SHADOW_SAME,
275                 span,
276                 &format!(
277                     "`{}` is shadowed by itself in `{}`",
278                     snippet(cx, pattern_span, "_"),
279                     snippet(cx, expr.span, "..")
280                 ),
281                 |diag| {
282                     diag.span_note(prev_span, "previous binding is here");
283                 },
284             );
285         } else if contains_name(name, expr) {
286             span_lint_and_then(
287                 cx,
288                 SHADOW_REUSE,
289                 pattern_span,
290                 &format!(
291                     "`{}` is shadowed by `{}` which reuses the original value",
292                     snippet(cx, pattern_span, "_"),
293                     snippet(cx, expr.span, "..")
294                 ),
295                 |diag| {
296                     diag.span_note(expr.span, "initialization happens here");
297                     diag.span_note(prev_span, "previous binding is here");
298                 },
299             );
300         } else {
301             span_lint_and_then(
302                 cx,
303                 SHADOW_UNRELATED,
304                 pattern_span,
305                 &format!(
306                     "`{}` is shadowed by `{}`",
307                     snippet(cx, pattern_span, "_"),
308                     snippet(cx, expr.span, "..")
309                 ),
310                 |diag| {
311                     diag.span_note(expr.span, "initialization happens here");
312                     diag.span_note(prev_span, "previous binding is here");
313                 },
314             );
315         }
316     } else {
317         span_lint_and_then(
318             cx,
319             SHADOW_UNRELATED,
320             span,
321             &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
322             |diag| {
323                 diag.span_note(prev_span, "previous binding is here");
324             },
325         );
326     }
327 }
328
329 fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) {
330     if in_external_macro(cx.sess(), expr.span) {
331         return;
332     }
333     match expr.kind {
334         ExprKind::Unary(_, ref e)
335         | ExprKind::Field(ref e, _)
336         | ExprKind::AddrOf(_, _, ref e)
337         | ExprKind::Box(ref e) => check_expr(cx, e, bindings),
338         ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
339         // ExprKind::Call
340         // ExprKind::MethodCall
341         ExprKind::Array(v) | ExprKind::Tup(v) => {
342             for e in v {
343                 check_expr(cx, e, bindings)
344             }
345         },
346         ExprKind::Match(ref init, arms, _) => {
347             check_expr(cx, init, bindings);
348             let len = bindings.len();
349             for arm in arms {
350                 check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings);
351                 // This is ugly, but needed to get the right type
352                 if let Some(ref guard) = arm.guard {
353                     match guard {
354                         Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
355                     }
356                 }
357                 check_expr(cx, &arm.body, bindings);
358                 bindings.truncate(len);
359             }
360         },
361         _ => (),
362     }
363 }
364
365 fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Name, Span)>) {
366     match ty.kind {
367         TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
368         TyKind::Array(ref fty, ref anon_const) => {
369             check_ty(cx, fty, bindings);
370             check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
371         },
372         TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
373             check_ty(cx, mty, bindings)
374         },
375         TyKind::Tup(tup) => {
376             for t in tup {
377                 check_ty(cx, t, bindings)
378             }
379         },
380         TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
381         _ => (),
382     }
383 }
384
385 fn is_self_shadow(name: Name, expr: &Expr<'_>) -> bool {
386     match expr.kind {
387         ExprKind::Box(ref inner) | ExprKind::AddrOf(_, _, ref inner) => is_self_shadow(name, inner),
388         ExprKind::Block(ref block, _) => {
389             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
390         },
391         ExprKind::Unary(op, ref inner) => (UnOp::UnDeref == op) && is_self_shadow(name, inner),
392         ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
393         _ => false,
394     }
395 }
396
397 fn path_eq_name(name: Name, path: &Path<'_>) -> bool {
398     !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
399 }