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