]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/misc.rs
Rollup merge of #99880 - compiler-errors:escape-ascii-is-not-exact-size-iterator...
[rust.git] / src / tools / clippy / clippy_lints / src / misc.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_hir_and_then};
2 use clippy_utils::source::{snippet, snippet_opt};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::intravisit::FnKind;
6 use rustc_hir::{
7     self as hir, def, BinOpKind, BindingAnnotation, Body, ByRef, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind,
8     Stmt, StmtKind, TyKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::hygiene::DesugaringKind;
14 use rustc_span::source_map::{ExpnKind, Span};
15
16 use clippy_utils::sugg::Sugg;
17 use clippy_utils::{get_parent_expr, in_constant, is_integer_literal, iter_input_pats, last_path_segment, SpanlessEq};
18
19 declare_clippy_lint! {
20     /// ### What it does
21     /// Checks for function arguments and let bindings denoted as
22     /// `ref`.
23     ///
24     /// ### Why is this bad?
25     /// The `ref` declaration makes the function take an owned
26     /// value, but turns the argument into a reference (which means that the value
27     /// is destroyed when exiting the function). This adds not much value: either
28     /// take a reference type, or take an owned value and create references in the
29     /// body.
30     ///
31     /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
32     /// type of `x` is more obvious with the former.
33     ///
34     /// ### Known problems
35     /// If the argument is dereferenced within the function,
36     /// removing the `ref` will lead to errors. This can be fixed by removing the
37     /// dereferences, e.g., changing `*x` to `x` within the function.
38     ///
39     /// ### Example
40     /// ```rust
41     /// fn foo(ref _x: u8) {}
42     /// ```
43     ///
44     /// Use instead:
45     /// ```rust
46     /// fn foo(_x: &u8) {}
47     /// ```
48     #[clippy::version = "pre 1.29.0"]
49     pub TOPLEVEL_REF_ARG,
50     style,
51     "an entire binding declared as `ref`, in a function argument or a `let` statement"
52 }
53 declare_clippy_lint! {
54     /// ### What it does
55     /// Checks for the use of bindings with a single leading
56     /// underscore.
57     ///
58     /// ### Why is this bad?
59     /// A single leading underscore is usually used to indicate
60     /// that a binding will not be used. Using such a binding breaks this
61     /// expectation.
62     ///
63     /// ### Known problems
64     /// The lint does not work properly with desugaring and
65     /// macro, it has been allowed in the mean time.
66     ///
67     /// ### Example
68     /// ```rust
69     /// let _x = 0;
70     /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
71     ///                 // underscore. We should rename `_x` to `x`
72     /// ```
73     #[clippy::version = "pre 1.29.0"]
74     pub USED_UNDERSCORE_BINDING,
75     pedantic,
76     "using a binding which is prefixed with an underscore"
77 }
78
79 declare_clippy_lint! {
80     /// ### What it does
81     /// Checks for the use of short circuit boolean conditions as
82     /// a
83     /// statement.
84     ///
85     /// ### Why is this bad?
86     /// Using a short circuit boolean condition as a statement
87     /// may hide the fact that the second part is executed or not depending on the
88     /// outcome of the first part.
89     ///
90     /// ### Example
91     /// ```rust,ignore
92     /// f() && g(); // We should write `if f() { g(); }`.
93     /// ```
94     #[clippy::version = "pre 1.29.0"]
95     pub SHORT_CIRCUIT_STATEMENT,
96     complexity,
97     "using a short circuit boolean condition as a statement"
98 }
99
100 declare_clippy_lint! {
101     /// ### What it does
102     /// Catch casts from `0` to some pointer type
103     ///
104     /// ### Why is this bad?
105     /// This generally means `null` and is better expressed as
106     /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
107     ///
108     /// ### Example
109     /// ```rust
110     /// let a = 0 as *const u32;
111     /// ```
112     ///
113     /// Use instead:
114     /// ```rust
115     /// let a = std::ptr::null::<u32>();
116     /// ```
117     #[clippy::version = "pre 1.29.0"]
118     pub ZERO_PTR,
119     style,
120     "using `0 as *{const, mut} T`"
121 }
122
123 declare_lint_pass!(MiscLints => [
124     TOPLEVEL_REF_ARG,
125     USED_UNDERSCORE_BINDING,
126     SHORT_CIRCUIT_STATEMENT,
127     ZERO_PTR,
128 ]);
129
130 impl<'tcx> LateLintPass<'tcx> for MiscLints {
131     fn check_fn(
132         &mut self,
133         cx: &LateContext<'tcx>,
134         k: FnKind<'tcx>,
135         decl: &'tcx FnDecl<'_>,
136         body: &'tcx Body<'_>,
137         span: Span,
138         _: HirId,
139     ) {
140         if let FnKind::Closure = k {
141             // Does not apply to closures
142             return;
143         }
144         if in_external_macro(cx.tcx.sess, span) {
145             return;
146         }
147         for arg in iter_input_pats(decl, body) {
148             if let PatKind::Binding(BindingAnnotation(ByRef::Yes, _), ..) = arg.pat.kind {
149                 span_lint(
150                     cx,
151                     TOPLEVEL_REF_ARG,
152                     arg.pat.span,
153                     "`ref` directly on a function argument is ignored. \
154                     Consider using a reference type instead",
155                 );
156             }
157         }
158     }
159
160     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
161         if_chain! {
162             if !in_external_macro(cx.tcx.sess, stmt.span);
163             if let StmtKind::Local(local) = stmt.kind;
164             if let PatKind::Binding(BindingAnnotation(ByRef::Yes, mutabl), .., name, None) = local.pat.kind;
165             if let Some(init) = local.init;
166             then {
167                 // use the macro callsite when the init span (but not the whole local span)
168                 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
169                 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
170                     Sugg::hir_with_macro_callsite(cx, init, "..")
171                 } else {
172                     Sugg::hir(cx, init, "..")
173                 };
174                 let (mutopt, initref) = if mutabl == Mutability::Mut {
175                     ("mut ", sugg_init.mut_addr())
176                 } else {
177                     ("", sugg_init.addr())
178                 };
179                 let tyopt = if let Some(ty) = local.ty {
180                     format!(": &{mutopt}{ty}", ty=snippet(cx, ty.span, ".."))
181                 } else {
182                     String::new()
183                 };
184                 span_lint_hir_and_then(
185                     cx,
186                     TOPLEVEL_REF_ARG,
187                     init.hir_id,
188                     local.pat.span,
189                     "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
190                     |diag| {
191                         diag.span_suggestion(
192                             stmt.span,
193                             "try",
194                             format!(
195                                 "let {name}{tyopt} = {initref};",
196                                 name=snippet(cx, name.span, ".."),
197                             ),
198                             Applicability::MachineApplicable,
199                         );
200                     }
201                 );
202             }
203         };
204         if_chain! {
205             if let StmtKind::Semi(expr) = stmt.kind;
206             if let ExprKind::Binary(ref binop, a, b) = expr.kind;
207             if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
208             if let Some(sugg) = Sugg::hir_opt(cx, a);
209             then {
210                 span_lint_hir_and_then(
211                     cx,
212                     SHORT_CIRCUIT_STATEMENT,
213                     expr.hir_id,
214                     stmt.span,
215                     "boolean short circuit operator in statement may be clearer using an explicit test",
216                     |diag| {
217                         let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
218                         diag.span_suggestion(
219                             stmt.span,
220                             "replace it with",
221                             format!(
222                                 "if {sugg} {{ {}; }}",
223                                 &snippet(cx, b.span, ".."),
224                             ),
225                             Applicability::MachineApplicable, // snippet
226                         );
227                     });
228             }
229         };
230     }
231
232     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
233         if let ExprKind::Cast(e, ty) = expr.kind {
234             check_cast(cx, expr.span, e, ty);
235             return;
236         }
237         if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
238             // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
239             return;
240         }
241         let sym;
242         let binding = match expr.kind {
243             ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
244                 let binding = last_path_segment(qpath).ident.as_str();
245                 if binding.starts_with('_') &&
246                     !binding.starts_with("__") &&
247                     binding != "_result" && // FIXME: #944
248                     is_used(cx, expr) &&
249                     // don't lint if the declaration is in a macro
250                     non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
251                 {
252                     Some(binding)
253                 } else {
254                     None
255                 }
256             },
257             ExprKind::Field(_, ident) => {
258                 sym = ident.name;
259                 let name = sym.as_str();
260                 if name.starts_with('_') && !name.starts_with("__") {
261                     Some(name)
262                 } else {
263                     None
264                 }
265             },
266             _ => None,
267         };
268         if let Some(binding) = binding {
269             span_lint(
270                 cx,
271                 USED_UNDERSCORE_BINDING,
272                 expr.span,
273                 &format!(
274                     "used binding `{binding}` which is prefixed with an underscore. A leading \
275                      underscore signals that a binding will not be used"
276                 ),
277             );
278         }
279     }
280 }
281
282 /// Heuristic to see if an expression is used. Should be compatible with
283 /// `unused_variables`'s idea
284 /// of what it means for an expression to be "used".
285 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
286     get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
287         ExprKind::Assign(_, rhs, _) | ExprKind::AssignOp(_, _, rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
288         _ => is_used(cx, parent),
289     })
290 }
291
292 /// Tests whether an expression is in a macro expansion (e.g., something
293 /// generated by `#[derive(...)]` or the like).
294 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
295     use rustc_span::hygiene::MacroKind;
296     if expr.span.from_expansion() {
297         let data = expr.span.ctxt().outer_expn_data();
298         matches!(data.kind, ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, _))
299     } else {
300         false
301     }
302 }
303
304 /// Tests whether `res` is a variable defined outside a macro.
305 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
306     if let def::Res::Local(id) = res {
307         !cx.tcx.hir().span(id).from_expansion()
308     } else {
309         false
310     }
311 }
312
313 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
314     if_chain! {
315         if let TyKind::Ptr(ref mut_ty) = ty.kind;
316         if is_integer_literal(e, 0);
317         if !in_constant(cx, e.hir_id);
318         then {
319             let (msg, sugg_fn) = match mut_ty.mutbl {
320                 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
321                 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
322             };
323
324             let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
325                 (format!("{sugg_fn}()"), Applicability::MachineApplicable)
326             } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
327                 (format!("{sugg_fn}::<{mut_ty_snip}>()"), Applicability::MachineApplicable)
328             } else {
329                 // `MaybeIncorrect` as type inference may not work with the suggested code
330                 (format!("{sugg_fn}()"), Applicability::MaybeIncorrect)
331             };
332             span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
333         }
334     }
335 }