Skip to content

Commit

Permalink
Auto merge of rust-lang#13069 - Jarcho:misc_small4, r=Manishearth
Browse files Browse the repository at this point in the history
Misc refactorings part 4

And even more rearrangements to check the HIR tree before other checks.

changelog: none
  • Loading branch information
bors committed Jul 9, 2024
2 parents 87f8a5b + eda45aa commit 8fa406b
Show file tree
Hide file tree
Showing 19 changed files with 104 additions and 150 deletions.
19 changes: 8 additions & 11 deletions clippy_lints/src/len_zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,9 @@ declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMP

impl<'tcx> LateLintPass<'tcx> for LenZero {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if item.span.from_expansion() {
return;
}

if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind {
if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind
&& !item.span.from_expansion()
{
check_trait_items(cx, item, trait_items);
}
}
Expand Down Expand Up @@ -162,17 +160,14 @@ impl<'tcx> LateLintPass<'tcx> for LenZero {
}

fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if expr.span.from_expansion() {
return;
}

if let ExprKind::Let(lt) = expr.kind
&& has_is_empty(cx, lt.init)
&& match lt.pat.kind {
PatKind::Slice([], None, []) => true,
PatKind::Lit(lit) if is_empty_string(lit) => true,
_ => false,
}
&& !expr.span.from_expansion()
&& has_is_empty(cx, lt.init)
{
let mut applicability = Applicability::MachineApplicable;

Expand All @@ -190,7 +185,9 @@ impl<'tcx> LateLintPass<'tcx> for LenZero {
);
}

if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind {
if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind
&& !expr.span.from_expansion()
{
// expr.span might contains parenthesis, see issue #10529
let actual_span = span_without_enclosing_paren(cx, expr.span);
match cmp {
Expand Down
8 changes: 3 additions & 5 deletions clippy_lints/src/let_if_seq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,10 @@ declare_lint_pass!(LetIfSeq => [USELESS_LET_IF_SEQ]);

impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
let mut it = block.stmts.iter().peekable();
while let Some(stmt) = it.next() {
if let Some(expr) = it.peek()
&& let hir::StmtKind::Let(local) = stmt.kind
for [stmt, next] in block.stmts.array_windows::<2>() {
if let hir::StmtKind::Let(local) = stmt.kind
&& let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind
&& let hir::StmtKind::Expr(if_) = expr.kind
&& let hir::StmtKind::Expr(if_) = next.kind
&& let hir::ExprKind::If(
hir::Expr {
kind: hir::ExprKind::DropTemps(cond),
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/let_underscore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,9 @@ const SYNC_GUARD_PATHS: [&[&str]; 3] = [
impl<'tcx> LateLintPass<'tcx> for LetUnderscore {
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &LetStmt<'tcx>) {
if matches!(local.source, LocalSource::Normal)
&& !in_external_macro(cx.tcx.sess, local.span)
&& let PatKind::Wild = local.pat.kind
&& let Some(init) = local.init
&& !in_external_macro(cx.tcx.sess, local.span)
{
let init_ty = cx.typeck_results().expr_ty(init);
let contains_sync_guard = init_ty.walk().any(|inner| match inner.unpack() {
Expand Down
17 changes: 6 additions & 11 deletions clippy_lints/src/let_with_type_underscore.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::snippet;
use clippy_utils::is_from_proc_macro;
use rustc_hir::{LetStmt, TyKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::lint::in_external_macro;
Expand All @@ -25,19 +25,14 @@ declare_clippy_lint! {
}
declare_lint_pass!(UnderscoreTyped => [LET_WITH_TYPE_UNDERSCORE]);

impl LateLintPass<'_> for UnderscoreTyped {
fn check_local(&mut self, cx: &LateContext<'_>, local: &LetStmt<'_>) {
if !in_external_macro(cx.tcx.sess, local.span)
&& let Some(ty) = local.ty // Ensure that it has a type defined
impl<'tcx> LateLintPass<'tcx> for UnderscoreTyped {
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx LetStmt<'_>) {
if let Some(ty) = local.ty // Ensure that it has a type defined
&& let TyKind::Infer = &ty.kind // that type is '_'
&& local.span.eq_ctxt(ty.span)
&& !in_external_macro(cx.tcx.sess, local.span)
&& !is_from_proc_macro(cx, ty)
{
// NOTE: Using `is_from_proc_macro` on `init` will require that it's initialized,
// this doesn't. Alternatively, `WithSearchPat` can be implemented for `Ty`
if snippet(cx, ty.span, "_").trim() != "_" {
return;
}

span_lint_and_help(
cx,
LET_WITH_TYPE_UNDERSCORE,
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#![feature(if_let_guard)]
#![feature(is_sorted)]
#![feature(iter_intersperse)]
#![feature(iter_partition_in_place)]
#![feature(let_chains)]
#![feature(never_type)]
#![feature(rustc_private)]
Expand Down
16 changes: 6 additions & 10 deletions clippy_lints/src/literal_representation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,9 @@ impl_lint_pass!(LiteralDigitGrouping => [

impl EarlyLintPass for LiteralDigitGrouping {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
if in_external_macro(cx.sess(), expr.span) {
return;
}

if let ExprKind::Lit(lit) = expr.kind {
if let ExprKind::Lit(lit) = expr.kind
&& !in_external_macro(cx.sess(), expr.span)
{
self.check_lit(cx, lit, expr.span);
}
}
Expand Down Expand Up @@ -448,11 +446,9 @@ impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]

impl EarlyLintPass for DecimalLiteralRepresentation {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
if in_external_macro(cx.sess(), expr.span) {
return;
}

if let ExprKind::Lit(lit) = expr.kind {
if let ExprKind::Lit(lit) = expr.kind
&& !in_external_macro(cx.sess(), expr.span)
{
self.check_lit(cx, lit, expr.span);
}
}
Expand Down
5 changes: 1 addition & 4 deletions clippy_lints/src/manual_bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,10 @@ impl_lint_pass!(ManualBits => [MANUAL_BITS]);

impl<'tcx> LateLintPass<'tcx> for ManualBits {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if !self.msrv.meets(msrvs::MANUAL_BITS) {
return;
}

if let ExprKind::Binary(bin_op, left_expr, right_expr) = expr.kind
&& let BinOpKind::Mul = &bin_op.node
&& !in_external_macro(cx.sess(), expr.span)
&& self.msrv.meets(msrvs::MANUAL_BITS)
&& let ctxt = expr.span.ctxt()
&& left_expr.span.ctxt() == ctxt
&& right_expr.span.ctxt() == ctxt
Expand Down
29 changes: 13 additions & 16 deletions clippy_lints/src/manual_float_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,29 +82,26 @@ impl Variant {

impl<'tcx> LateLintPass<'tcx> for ManualFloatMethods {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
if !in_external_macro(cx.sess(), expr.span)
&& (
matches!(cx.tcx.constness(cx.tcx.hir().enclosing_body_owner(expr.hir_id)), Constness::NotConst)
|| cx.tcx.features().declared(sym!(const_float_classify))
) && let ExprKind::Binary(kind, lhs, rhs) = expr.kind
if let ExprKind::Binary(kind, lhs, rhs) = expr.kind
&& let ExprKind::Binary(lhs_kind, lhs_lhs, lhs_rhs) = lhs.kind
&& let ExprKind::Binary(rhs_kind, rhs_lhs, rhs_rhs) = rhs.kind
// Checking all possible scenarios using a function would be a hopeless task, as we have
// 16 possible alignments of constants/operands. For now, let's use `partition`.
&& let (operands, constants) = [lhs_lhs, lhs_rhs, rhs_lhs, rhs_rhs]
.into_iter()
.partition::<Vec<&Expr<'_>>, _>(|i| path_to_local(i).is_some())
&& let [first, second] = &*operands
&& let Some([const_1, const_2]) = constants
.into_iter()
.map(|i| constant(cx, cx.typeck_results(), i))
.collect::<Option<Vec<_>>>()
.as_deref()
&& let mut exprs = [lhs_lhs, lhs_rhs, rhs_lhs, rhs_rhs]
&& exprs.iter_mut().partition_in_place(|i| path_to_local(i).is_some()) == 2
&& !in_external_macro(cx.sess(), expr.span)
&& (
matches!(cx.tcx.constness(cx.tcx.hir().enclosing_body_owner(expr.hir_id)), Constness::NotConst)
|| cx.tcx.features().declared(sym!(const_float_classify))
)
&& let [first, second, const_1, const_2] = exprs
&& let Some(const_1) = constant(cx, cx.typeck_results(), const_1)
&& let Some(const_2) = constant(cx, cx.typeck_results(), const_2)
&& path_to_local(first).is_some_and(|f| path_to_local(second).is_some_and(|s| f == s))
// The actual infinity check, we also allow `NEG_INFINITY` before` INFINITY` just in
// case somebody does that for some reason
&& (is_infinity(const_1) && is_neg_infinity(const_2)
|| is_neg_infinity(const_1) && is_infinity(const_2))
&& (is_infinity(&const_1) && is_neg_infinity(&const_2)
|| is_neg_infinity(&const_1) && is_infinity(&const_2))
&& let Some(local_snippet) = snippet_opt(cx, first.span)
{
let variant = match (kind.node, lhs_kind.node, rhs_kind.node) {
Expand Down
6 changes: 2 additions & 4 deletions clippy_lints/src/manual_let_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,14 @@ declare_clippy_lint! {

impl<'tcx> QuestionMark {
pub(crate) fn check_manual_let_else(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'tcx>) {
if !self.msrv.meets(msrvs::LET_ELSE) || in_external_macro(cx.sess(), stmt.span) {
return;
}

if let StmtKind::Let(local) = stmt.kind
&& let Some(init) = local.init
&& local.els.is_none()
&& local.ty.is_none()
&& init.span.eq_ctxt(stmt.span)
&& let Some(if_let_or_match) = IfLetOrMatch::parse(cx, init)
&& self.msrv.meets(msrvs::LET_ELSE)
&& !in_external_macro(cx.sess(), stmt.span)
{
match if_let_or_match {
IfLetOrMatch::IfLet(if_let_expr, let_pat, if_then, if_else, ..) => {
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/manual_main_separator_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ impl_lint_pass!(ManualMainSeparatorStr => [MANUAL_MAIN_SEPARATOR_STR]);

impl LateLintPass<'_> for ManualMainSeparatorStr {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if self.msrv.meets(msrvs::PATH_MAIN_SEPARATOR_STR)
&& let (target, _) = peel_hir_expr_refs(expr)
&& is_trait_method(cx, target, sym::ToString)
&& let ExprKind::MethodCall(path, receiver, &[], _) = target.kind
let (target, _) = peel_hir_expr_refs(expr);
if let ExprKind::MethodCall(path, receiver, &[], _) = target.kind
&& path.ident.name == sym::to_string
&& let ExprKind::Path(QPath::Resolved(None, path)) = receiver.kind
&& let Res::Def(DefKind::Const, receiver_def_id) = path.res
&& is_trait_method(cx, target, sym::ToString)
&& self.msrv.meets(msrvs::PATH_MAIN_SEPARATOR_STR)
&& match_def_path(cx, receiver_def_id, &paths::PATH_MAIN_SEPARATOR)
&& let ty::Ref(_, ty, Mutability::Not) = cx.typeck_results().expr_ty_adjusted(expr).kind()
&& ty.is_str()
Expand Down
14 changes: 5 additions & 9 deletions clippy_lints/src/manual_non_exhaustive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,15 @@ impl_lint_pass!(ManualNonExhaustiveEnum => [MANUAL_NON_EXHAUSTIVE]);

impl EarlyLintPass for ManualNonExhaustiveStruct {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
if !self.msrv.meets(msrvs::NON_EXHAUSTIVE) {
return;
}

if let ast::ItemKind::Struct(variant_data, _) = &item.kind {
let (fields, delimiter) = match variant_data {
if let ast::ItemKind::Struct(variant_data, _) = &item.kind
&& let (fields, delimiter) = match variant_data {
ast::VariantData::Struct { fields, .. } => (&**fields, '{'),
ast::VariantData::Tuple(fields, _) => (&**fields, '('),
ast::VariantData::Unit(_) => return,
};
if fields.len() <= 1 {
return;
}
&& fields.len() > 1
&& self.msrv.meets(msrvs::NON_EXHAUSTIVE)
{
let mut iter = fields.iter().filter_map(|f| match f.vis.kind {
VisibilityKind::Public => None,
VisibilityKind::Inherited => Some(Ok(f)),
Expand Down
5 changes: 1 addition & 4 deletions clippy_lints/src/manual_range_patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,11 @@ impl Num {

impl LateLintPass<'_> for ManualRangePatterns {
fn check_pat(&mut self, cx: &LateContext<'_>, pat: &'_ rustc_hir::Pat<'_>) {
if in_external_macro(cx.sess(), pat.span) {
return;
}

// a pattern like 1 | 2 seems fine, lint if there are at least 3 alternatives
// or at least one range
if let PatKind::Or(pats) = pat.kind
&& (pats.len() >= 3 || pats.iter().any(|p| matches!(p.kind, PatKind::Range(..))))
&& !in_external_macro(cx.sess(), pat.span)
{
let mut min = Num::dummy(i128::MAX);
let mut max = Num::dummy(i128::MIN);
Expand Down
49 changes: 22 additions & 27 deletions clippy_lints/src/manual_rem_euclid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,35 +48,30 @@ impl_lint_pass!(ManualRemEuclid => [MANUAL_REM_EUCLID]);

impl<'tcx> LateLintPass<'tcx> for ManualRemEuclid {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if !self.msrv.meets(msrvs::REM_EUCLID) {
return;
}

if in_constant(cx, expr.hir_id) && !self.msrv.meets(msrvs::REM_EUCLID_CONST) {
return;
}

if in_external_macro(cx.sess(), expr.span) {
return;
}

// (x % c + c) % c
if let ExprKind::Binary(op1, expr1, right) = expr.kind
&& op1.node == BinOpKind::Rem
if let ExprKind::Binary(rem_op, rem_lhs, rem_rhs) = expr.kind
&& rem_op.node == BinOpKind::Rem
&& let ExprKind::Binary(add_op, add_lhs, add_rhs) = rem_lhs.kind
&& add_op.node == BinOpKind::Add
&& let ctxt = expr.span.ctxt()
&& expr1.span.ctxt() == ctxt
&& let Some(const1) = check_for_unsigned_int_constant(cx, right)
&& let ExprKind::Binary(op2, left, right) = expr1.kind
&& op2.node == BinOpKind::Add
&& let Some((const2, expr2)) = check_for_either_unsigned_int_constant(cx, left, right)
&& expr2.span.ctxt() == ctxt
&& let ExprKind::Binary(op3, expr3, right) = expr2.kind
&& op3.node == BinOpKind::Rem
&& let Some(const3) = check_for_unsigned_int_constant(cx, right)
&& rem_lhs.span.ctxt() == ctxt
&& rem_rhs.span.ctxt() == ctxt
&& add_lhs.span.ctxt() == ctxt
&& add_rhs.span.ctxt() == ctxt
&& !in_external_macro(cx.sess(), expr.span)
&& self.msrv.meets(msrvs::REM_EUCLID)
&& (self.msrv.meets(msrvs::REM_EUCLID_CONST) || !in_constant(cx, expr.hir_id))
&& let Some(const1) = check_for_unsigned_int_constant(cx, rem_rhs)
&& let Some((const2, add_other)) = check_for_either_unsigned_int_constant(cx, add_lhs, add_rhs)
&& let ExprKind::Binary(rem2_op, rem2_lhs, rem2_rhs) = add_other.kind
&& rem2_op.node == BinOpKind::Rem
&& const1 == const2
&& let Some(hir_id) = path_to_local(rem2_lhs)
&& let Some(const3) = check_for_unsigned_int_constant(cx, rem2_rhs)
// Also ensures the const is nonzero since zero can't be a divisor
&& const1 == const2 && const2 == const3
&& let Some(hir_id) = path_to_local(expr3)
&& let Node::Pat(_) = cx.tcx.hir_node(hir_id)
&& const2 == const3
&& rem2_lhs.span.ctxt() == ctxt
&& rem2_rhs.span.ctxt() == ctxt
{
// Apply only to params or locals with annotated types
match cx.tcx.parent_hir_node(hir_id) {
Expand All @@ -91,7 +86,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualRemEuclid {
};

let mut app = Applicability::MachineApplicable;
let rem_of = snippet_with_context(cx, expr3.span, ctxt, "_", &mut app).0;
let rem_of = snippet_with_context(cx, rem2_lhs.span, ctxt, "_", &mut app).0;
span_lint_and_sugg(
cx,
MANUAL_REM_EUCLID,
Expand Down
3 changes: 1 addition & 2 deletions clippy_lints/src/manual_retain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,8 @@ impl_lint_pass!(ManualRetain => [MANUAL_RETAIN]);
impl<'tcx> LateLintPass<'tcx> for ManualRetain {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
if let Assign(left_expr, collect_expr, _) = &expr.kind
&& let hir::ExprKind::MethodCall(seg, ..) = &collect_expr.kind
&& let hir::ExprKind::MethodCall(seg, target_expr, [], _) = &collect_expr.kind
&& seg.args.is_none()
&& let hir::ExprKind::MethodCall(_, target_expr, [], _) = &collect_expr.kind
&& let Some(collect_def_id) = cx.typeck_results().type_dependent_def_id(collect_expr.hir_id)
&& cx.tcx.is_diagnostic_item(sym::iterator_collect_fn, collect_def_id)
{
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/manual_slice_size_calculation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ declare_lint_pass!(ManualSliceSizeCalculation => [MANUAL_SLICE_SIZE_CALCULATION]

impl<'tcx> LateLintPass<'tcx> for ManualSliceSizeCalculation {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
// Does not apply inside const because size_of_val is not cost in stable.
if !in_constant(cx, expr.hir_id)
&& let ExprKind::Binary(ref op, left, right) = expr.kind
if let ExprKind::Binary(ref op, left, right) = expr.kind
&& BinOpKind::Mul == op.node
&& !expr.span.from_expansion()
// Does not apply inside const because size_of_val is not cost in stable.
&& !in_constant(cx, expr.hir_id)
&& let Some(receiver) = simplify(cx, left, right)
{
let ctxt = expr.span.ctxt();
Expand Down
7 changes: 2 additions & 5 deletions clippy_lints/src/manual_strip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,11 @@ enum StripKind {

impl<'tcx> LateLintPass<'tcx> for ManualStrip {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if !self.msrv.meets(msrvs::STR_STRIP_PREFIX) {
return;
}

if let Some(higher::If { cond, then, .. }) = higher::If::hir(expr)
&& let ExprKind::MethodCall(_, target_arg, [pattern], _) = cond.kind
&& let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(cond.hir_id)
&& let ExprKind::Path(target_path) = &target_arg.kind
&& self.msrv.meets(msrvs::STR_STRIP_PREFIX)
&& let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(cond.hir_id)
{
let strip_kind = if match_def_path(cx, method_def_id, &paths::STR_STARTS_WITH) {
StripKind::Prefix
Expand Down
Loading

0 comments on commit 8fa406b

Please sign in to comment.