rust-clippy/clippy_lints/src/misc.rs

343 lines
12 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_hir_and_then};
use clippy_utils::source::{snippet, snippet_opt};
2018-11-27 20:14:15 +00:00
use if_chain::if_chain;
2020-03-01 03:23:33 +00:00
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
2020-01-09 07:13:22 +00:00
use rustc_hir::intravisit::FnKind;
2020-02-21 08:39:38 +00:00
use rustc_hir::{
self as hir, def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, Stmt,
StmtKind, TyKind,
2020-02-21 08:39:38 +00:00
};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::lint::in_external_macro;
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::hygiene::DesugaringKind;
use rustc_span::source_map::{ExpnKind, Span};
use clippy_utils::sugg::Sugg;
use clippy_utils::{get_parent_expr, in_constant, iter_input_pats, last_path_segment, SpanlessEq};
2019-01-31 01:15:29 +00:00
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for function arguments and let bindings denoted as
/// `ref`.
///
/// ### Why is this bad?
/// The `ref` declaration makes the function take an owned
/// value, but turns the argument into a reference (which means that the value
/// is destroyed when exiting the function). This adds not much value: either
/// take a reference type, or take an owned value and create references in the
/// body.
///
/// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
/// type of `x` is more obvious with the former.
///
/// ### Known problems
/// If the argument is dereferenced within the function,
/// removing the `ref` will lead to errors. This can be fixed by removing the
2019-01-31 01:15:29 +00:00
/// dereferences, e.g., changing `*x` to `x` within the function.
///
/// ### Example
/// ```rust
/// fn foo(ref _x: u8) {}
/// ```
///
/// Use instead:
/// ```rust
/// fn foo(_x: &u8) {}
/// ```
#[clippy::version = "pre 1.29.0"]
pub TOPLEVEL_REF_ARG,
2018-03-28 13:24:26 +00:00
style,
"an entire binding declared as `ref`, in a function argument or a `let` statement"
}
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for the use of bindings with a single leading
/// underscore.
///
/// ### Why is this bad?
/// A single leading underscore is usually used to indicate
/// that a binding will not be used. Using such a binding breaks this
/// expectation.
///
/// ### Known problems
/// The lint does not work properly with desugaring and
/// macro, it has been allowed in the mean time.
///
/// ### Example
/// ```rust
/// let _x = 0;
/// let y = _x + 1; // Here we are using `_x`, even though it has a leading
/// // underscore. We should rename `_x` to `x`
/// ```
#[clippy::version = "pre 1.29.0"]
pub USED_UNDERSCORE_BINDING,
2018-03-28 13:24:26 +00:00
pedantic,
"using a binding which is prefixed with an underscore"
}
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for the use of short circuit boolean conditions as
/// a
/// statement.
///
/// ### Why is this bad?
/// Using a short circuit boolean condition as a statement
/// may hide the fact that the second part is executed or not depending on the
/// outcome of the first part.
///
/// ### Example
/// ```rust,ignore
/// f() && g(); // We should write `if f() { g(); }`.
/// ```
#[clippy::version = "pre 1.29.0"]
pub SHORT_CIRCUIT_STATEMENT,
2018-03-28 13:24:26 +00:00
complexity,
"using a short circuit boolean condition as a statement"
}
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Catch casts from `0` to some pointer type
///
/// ### Why is this bad?
/// This generally means `null` and is better expressed as
/// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
///
/// ### Example
/// ```rust
/// let a = 0 as *const u32;
/// ```
///
/// Use instead:
/// ```rust
/// let a = std::ptr::null::<u32>();
/// ```
#[clippy::version = "pre 1.29.0"]
pub ZERO_PTR,
2018-03-28 13:24:26 +00:00
style,
2020-01-06 06:30:43 +00:00
"using `0 as *{const, mut} T`"
}
2019-04-08 20:43:55 +00:00
declare_lint_pass!(MiscLints => [
TOPLEVEL_REF_ARG,
USED_UNDERSCORE_BINDING,
SHORT_CIRCUIT_STATEMENT,
ZERO_PTR,
]);
impl<'tcx> LateLintPass<'tcx> for MiscLints {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
k: FnKind<'tcx>,
2019-12-30 04:02:10 +00:00
decl: &'tcx FnDecl<'_>,
2019-12-22 14:42:41 +00:00
body: &'tcx Body<'_>,
span: Span,
2019-02-20 10:11:11 +00:00
_: HirId,
) {
2020-11-27 08:24:42 +00:00
if let FnKind::Closure = k {
// Does not apply to closures
2016-01-04 04:26:12 +00:00
return;
}
if in_external_macro(cx.tcx.sess, span) {
return;
}
for arg in iter_input_pats(decl, body) {
if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind {
span_lint(
cx,
TOPLEVEL_REF_ARG,
arg.pat.span,
"`ref` directly on a function argument is ignored. \
Consider using a reference type instead",
);
}
}
}
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if_chain! {
if !in_external_macro(cx.tcx.sess, stmt.span);
if let StmtKind::Local(local) = stmt.kind;
2019-09-27 15:16:06 +00:00
if let PatKind::Binding(an, .., name, None) = local.pat.kind;
if let Some(init) = local.init;
if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut;
then {
// use the macro callsite when the init span (but not the whole local span)
// comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
Sugg::hir_with_macro_callsite(cx, init, "..")
} else {
Sugg::hir(cx, init, "..")
};
let (mutopt, initref) = if an == BindingAnnotation::RefMut {
("mut ", sugg_init.mut_addr())
} else {
("", sugg_init.addr())
};
let tyopt = if let Some(ty) = local.ty {
format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, ".."))
} else {
String::new()
};
span_lint_hir_and_then(
cx,
TOPLEVEL_REF_ARG,
init.hir_id,
local.pat.span,
"`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
|diag| {
diag.span_suggestion(
stmt.span,
"try",
format!(
"let {name}{tyopt} = {initref};",
name=snippet(cx, name.span, ".."),
tyopt=tyopt,
initref=initref,
),
Applicability::MachineApplicable,
);
}
);
}
};
if_chain! {
if let StmtKind::Semi(expr) = stmt.kind;
if let ExprKind::Binary(ref binop, a, b) = expr.kind;
2018-07-12 07:50:09 +00:00
if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
if let Some(sugg) = Sugg::hir_opt(cx, a);
then {
span_lint_hir_and_then(
cx,
SHORT_CIRCUIT_STATEMENT,
expr.hir_id,
stmt.span,
"boolean short circuit operator in statement may be clearer using an explicit test",
|diag| {
2018-07-12 07:50:09 +00:00
let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
diag.span_suggestion(
stmt.span,
2018-09-18 15:07:54 +00:00
"replace it with",
format!(
"if {} {{ {}; }}",
2018-10-09 02:04:29 +00:00
sugg,
2018-09-18 15:07:54 +00:00
&snippet(cx, b.span, ".."),
),
Applicability::MachineApplicable, // snippet
2018-09-18 15:07:54 +00:00
);
});
}
};
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Cast(e, ty) = expr.kind {
check_cast(cx, expr.span, e, ty);
return;
}
if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
// Don't lint things expanded by #[derive(...)], etc or `await` desugaring
return;
}
let sym;
2019-09-27 15:16:06 +00:00
let binding = match expr.kind {
ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
2018-06-28 13:46:58 +00:00
let binding = last_path_segment(qpath).ident.as_str();
2016-12-02 16:38:31 +00:00
if binding.starts_with('_') &&
!binding.starts_with("__") &&
2017-03-09 09:58:31 +00:00
binding != "_result" && // FIXME: #944
2016-12-02 16:38:31 +00:00
is_used(cx, expr) &&
// don't lint if the declaration is in a macro
non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
2017-08-09 07:30:56 +00:00
{
2016-12-02 16:38:31 +00:00
Some(binding)
} else {
None
}
2016-12-20 17:21:30 +00:00
},
2018-07-12 07:30:57 +00:00
ExprKind::Field(_, ident) => {
sym = ident.name;
let name = sym.as_str();
if name.starts_with('_') && !name.starts_with("__") {
Some(name)
} else {
None
}
2016-12-20 17:21:30 +00:00
},
_ => None,
};
if let Some(binding) = binding {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
USED_UNDERSCORE_BINDING,
expr.span,
&format!(
"used binding `{}` which is prefixed with an underscore. A leading \
underscore signals that a binding will not be used",
2017-08-09 07:30:56 +00:00
binding
),
);
}
}
}
2017-08-09 07:30:56 +00:00
/// Heuristic to see if an expression is used. Should be compatible with
/// `unused_variables`'s idea
/// of what it means for an expression to be "used".
fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
ExprKind::Assign(_, rhs, _) | ExprKind::AssignOp(_, _, rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
_ => is_used(cx, parent),
})
}
2019-01-31 01:15:29 +00:00
/// Tests whether an expression is in a macro expansion (e.g., something
2019-03-10 17:19:47 +00:00
/// generated by `#[derive(...)]` or the like).
2019-12-27 07:12:26 +00:00
fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
2019-12-31 00:17:56 +00:00
use rustc_span::hygiene::MacroKind;
if expr.span.from_expansion() {
let data = expr.span.ctxt().outer_expn_data();
matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
} else {
false
}
}
2016-06-15 14:27:56 +00:00
/// Tests whether `res` is a variable defined outside a macro.
fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
if let def::Res::Local(id) = res {
2019-08-19 16:30:32 +00:00
!cx.tcx.hir().span(id).from_expansion()
} else {
false
2016-06-15 14:27:56 +00:00
}
}
fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
if_chain! {
2019-10-02 15:38:00 +00:00
if let TyKind::Ptr(ref mut_ty) = ty.kind;
2019-09-27 15:16:06 +00:00
if let ExprKind::Lit(ref lit) = e.kind;
2019-10-02 15:38:00 +00:00
if let LitKind::Int(0, _) = lit.node;
2019-02-24 18:43:15 +00:00
if !in_constant(cx, e.hir_id);
then {
2019-10-02 15:38:00 +00:00
let (msg, sugg_fn) = match mut_ty.mutbl {
Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
};
2019-10-02 15:38:00 +00:00
let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
(format!("{}()", sugg_fn), Applicability::MachineApplicable)
} else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
(format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
} else {
// `MaybeIncorrect` as type inference may not work with the suggested code
(format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
};
span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
}
}
}