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;
7 self as hir, def, BinOpKind, BindingAnnotation, Body, ByRef, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind,
8 Stmt, StmtKind, TyKind,
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};
16 use clippy_utils::sugg::Sugg;
18 get_parent_expr, in_constant, is_integer_literal, is_no_std_crate, iter_input_pats, last_path_segment, SpanlessEq,
21 declare_clippy_lint! {
23 /// Checks for function arguments and let bindings denoted as
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
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.
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.
43 /// fn foo(ref _x: u8) {}
48 /// fn foo(_x: &u8) {}
50 #[clippy::version = "pre 1.29.0"]
53 "an entire binding declared as `ref`, in a function argument or a `let` statement"
55 declare_clippy_lint! {
57 /// Checks for the use of bindings with a single leading
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
65 /// ### Known problems
66 /// The lint does not work properly with desugaring and
67 /// macro, it has been allowed in the mean time.
72 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
73 /// // underscore. We should rename `_x` to `x`
75 #[clippy::version = "pre 1.29.0"]
76 pub USED_UNDERSCORE_BINDING,
78 "using a binding which is prefixed with an underscore"
81 declare_clippy_lint! {
83 /// Checks for the use of short circuit boolean conditions as
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.
94 /// f() && g(); // We should write `if f() { g(); }`.
96 #[clippy::version = "pre 1.29.0"]
97 pub SHORT_CIRCUIT_STATEMENT,
99 "using a short circuit boolean condition as a statement"
102 declare_clippy_lint! {
104 /// Catch casts from `0` to some pointer type
106 /// ### Why is this bad?
107 /// This generally means `null` and is better expressed as
108 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
112 /// let a = 0 as *const u32;
117 /// let a = std::ptr::null::<u32>();
119 #[clippy::version = "pre 1.29.0"]
122 "using `0 as *{const, mut} T`"
125 pub struct LintPass {
126 std_or_core: &'static str,
128 impl Default for LintPass {
129 fn default() -> Self {
130 Self { std_or_core: "std" }
133 impl_lint_pass!(LintPass => [
135 USED_UNDERSCORE_BINDING,
136 SHORT_CIRCUIT_STATEMENT,
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";
149 cx: &LateContext<'tcx>,
151 decl: &'tcx FnDecl<'_>,
152 body: &'tcx Body<'_>,
156 if let FnKind::Closure = k {
157 // Does not apply to closures
160 if in_external_macro(cx.tcx.sess, span) {
163 for arg in iter_input_pats(decl, body) {
164 if let PatKind::Binding(BindingAnnotation(ByRef::Yes, _), ..) = arg.pat.kind {
169 "`ref` directly on a function argument is ignored. \
170 Consider using a reference type instead",
176 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
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;
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, "..")
188 Sugg::hir(cx, init, "..")
190 let (mutopt, initref) = if mutabl == Mutability::Mut {
191 ("mut ", sugg_init.mut_addr())
193 ("", sugg_init.addr())
195 let tyopt = if let Some(ty) = local.ty {
196 format!(": &{mutopt}{ty}", ty=snippet(cx, ty.span, ".."))
200 span_lint_hir_and_then(
205 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
207 diag.span_suggestion(
211 "let {name}{tyopt} = {initref};",
212 name=snippet(cx, name.span, ".."),
214 Applicability::MachineApplicable,
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);
226 span_lint_hir_and_then(
228 SHORT_CIRCUIT_STATEMENT,
231 "boolean short circuit operator in statement may be clearer using an explicit test",
233 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
234 diag.span_suggestion(
238 "if {sugg} {{ {}; }}",
239 &snippet(cx, b.span, ".."),
241 Applicability::MachineApplicable, // snippet
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);
253 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
254 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
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
265 // don't lint if the declaration is in a macro
266 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
273 ExprKind::Field(_, ident) => {
275 let name = sym.as_str();
276 if name.starts_with('_') && !name.starts_with("__") {
284 if let Some(binding) = binding {
287 USED_UNDERSCORE_BINDING,
290 "used binding `{binding}` which is prefixed with an underscore. A leading \
291 underscore signals that a binding will not be used"
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),
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, _))
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()
330 fn check_cast(&self, cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
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);
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"),
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)
346 // `MaybeIncorrect` as type inference may not work with the suggested code
347 (format!("{}::{sugg_fn}()", self.std_or_core), Applicability::MaybeIncorrect)
349 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);