]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/shadow.rs
Rollup merge of #74361 - GuillaumeGomez:theme-logo, r=Manishearth
[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.typeck_results().node_type_opt(pat_id);
168     var_ty.map_or(false, |var_ty| !matches!(var_ty.kind, ty::Adt(..)))
169 }
170
171 fn check_pat<'tcx>(
172     cx: &LateContext<'tcx>,
173     pat: &'tcx Pat<'_>,
174     init: Option<&'tcx Expr<'_>>,
175     span: Span,
176     bindings: &mut Vec<(Name, Span)>,
177 ) {
178     // TODO: match more stuff / destructuring
179     match pat.kind {
180         PatKind::Binding(.., ident, ref inner) => {
181             let name = ident.name;
182             if is_binding(cx, pat.hir_id) {
183                 let mut new_binding = true;
184                 for tup in bindings.iter_mut() {
185                     if tup.0 == name {
186                         lint_shadow(cx, name, span, pat.span, init, tup.1);
187                         tup.1 = ident.span;
188                         new_binding = false;
189                         break;
190                     }
191                 }
192                 if new_binding {
193                     bindings.push((name, ident.span));
194                 }
195             }
196             if let Some(ref p) = *inner {
197                 check_pat(cx, p, init, span, bindings);
198             }
199         },
200         PatKind::Struct(_, pfields, _) => {
201             if let Some(init_struct) = init {
202                 if let ExprKind::Struct(_, ref efields, _) = init_struct.kind {
203                     for field in pfields {
204                         let name = field.ident.name;
205                         let efield = efields
206                             .iter()
207                             .find_map(|f| if f.ident.name == name { Some(&*f.expr) } else { None });
208                         check_pat(cx, &field.pat, efield, span, bindings);
209                     }
210                 } else {
211                     for field in pfields {
212                         check_pat(cx, &field.pat, init, span, bindings);
213                     }
214                 }
215             } else {
216                 for field in pfields {
217                     check_pat(cx, &field.pat, None, span, bindings);
218                 }
219             }
220         },
221         PatKind::Tuple(inner, _) => {
222             if let Some(init_tup) = init {
223                 if let ExprKind::Tup(ref tup) = init_tup.kind {
224                     for (i, p) in inner.iter().enumerate() {
225                         check_pat(cx, p, Some(&tup[i]), p.span, bindings);
226                     }
227                 } else {
228                     for p in inner {
229                         check_pat(cx, p, init, span, bindings);
230                     }
231                 }
232             } else {
233                 for p in inner {
234                     check_pat(cx, p, None, span, bindings);
235                 }
236             }
237         },
238         PatKind::Box(ref inner) => {
239             if let Some(initp) = init {
240                 if let ExprKind::Box(ref inner_init) = initp.kind {
241                     check_pat(cx, inner, Some(&**inner_init), span, bindings);
242                 } else {
243                     check_pat(cx, inner, init, span, bindings);
244                 }
245             } else {
246                 check_pat(cx, inner, init, span, bindings);
247             }
248         },
249         PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
250         // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
251         _ => (),
252     }
253 }
254
255 fn lint_shadow<'tcx>(
256     cx: &LateContext<'tcx>,
257     name: Name,
258     span: Span,
259     pattern_span: Span,
260     init: Option<&'tcx Expr<'_>>,
261     prev_span: Span,
262 ) {
263     if let Some(expr) = init {
264         if is_self_shadow(name, expr) {
265             span_lint_and_then(
266                 cx,
267                 SHADOW_SAME,
268                 span,
269                 &format!(
270                     "`{}` is shadowed by itself in `{}`",
271                     snippet(cx, pattern_span, "_"),
272                     snippet(cx, expr.span, "..")
273                 ),
274                 |diag| {
275                     diag.span_note(prev_span, "previous binding is here");
276                 },
277             );
278         } else if contains_name(name, expr) {
279             span_lint_and_then(
280                 cx,
281                 SHADOW_REUSE,
282                 pattern_span,
283                 &format!(
284                     "`{}` is shadowed by `{}` which reuses the original value",
285                     snippet(cx, pattern_span, "_"),
286                     snippet(cx, expr.span, "..")
287                 ),
288                 |diag| {
289                     diag.span_note(expr.span, "initialization happens here");
290                     diag.span_note(prev_span, "previous binding is here");
291                 },
292             );
293         } else {
294             span_lint_and_then(
295                 cx,
296                 SHADOW_UNRELATED,
297                 pattern_span,
298                 &format!(
299                     "`{}` is shadowed by `{}`",
300                     snippet(cx, pattern_span, "_"),
301                     snippet(cx, expr.span, "..")
302                 ),
303                 |diag| {
304                     diag.span_note(expr.span, "initialization happens here");
305                     diag.span_note(prev_span, "previous binding is here");
306                 },
307             );
308         }
309     } else {
310         span_lint_and_then(
311             cx,
312             SHADOW_UNRELATED,
313             span,
314             &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
315             |diag| {
316                 diag.span_note(prev_span, "previous binding is here");
317             },
318         );
319     }
320 }
321
322 fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) {
323     if in_external_macro(cx.sess(), expr.span) {
324         return;
325     }
326     match expr.kind {
327         ExprKind::Unary(_, ref e)
328         | ExprKind::Field(ref e, _)
329         | ExprKind::AddrOf(_, _, ref e)
330         | ExprKind::Box(ref e) => check_expr(cx, e, bindings),
331         ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, _, _) => check_block(cx, block, bindings),
332         // ExprKind::Call
333         // ExprKind::MethodCall
334         ExprKind::Array(v) | ExprKind::Tup(v) => {
335             for e in v {
336                 check_expr(cx, e, bindings)
337             }
338         },
339         ExprKind::Match(ref init, arms, _) => {
340             check_expr(cx, init, bindings);
341             let len = bindings.len();
342             for arm in arms {
343                 check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings);
344                 // This is ugly, but needed to get the right type
345                 if let Some(ref guard) = arm.guard {
346                     match guard {
347                         Guard::If(if_expr) => check_expr(cx, if_expr, bindings),
348                     }
349                 }
350                 check_expr(cx, &arm.body, bindings);
351                 bindings.truncate(len);
352             }
353         },
354         _ => (),
355     }
356 }
357
358 fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: &'tcx Ty<'_>, bindings: &mut Vec<(Name, Span)>) {
359     match ty.kind {
360         TyKind::Slice(ref sty) => check_ty(cx, sty, bindings),
361         TyKind::Array(ref fty, ref anon_const) => {
362             check_ty(cx, fty, bindings);
363             check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings);
364         },
365         TyKind::Ptr(MutTy { ty: ref mty, .. }) | TyKind::Rptr(_, MutTy { ty: ref mty, .. }) => {
366             check_ty(cx, mty, bindings)
367         },
368         TyKind::Tup(tup) => {
369             for t in tup {
370                 check_ty(cx, t, bindings)
371             }
372         },
373         TyKind::Typeof(ref anon_const) => check_expr(cx, &cx.tcx.hir().body(anon_const.body).value, bindings),
374         _ => (),
375     }
376 }
377
378 fn is_self_shadow(name: Name, expr: &Expr<'_>) -> bool {
379     match expr.kind {
380         ExprKind::Box(ref inner) | ExprKind::AddrOf(_, _, ref inner) => is_self_shadow(name, inner),
381         ExprKind::Block(ref block, _) => {
382             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |e| is_self_shadow(name, e))
383         },
384         ExprKind::Unary(op, ref inner) => (UnOp::UnDeref == op) && is_self_shadow(name, inner),
385         ExprKind::Path(QPath::Resolved(_, ref path)) => path_eq_name(name, path),
386         _ => false,
387     }
388 }
389
390 fn path_eq_name(name: Name, path: &Path<'_>) -> bool {
391     !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str()
392 }