Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit c7e3e30

Browse files
committed
Add the lint logic
1 parent 484c82e commit c7e3e30

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed
Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
1-
use rustc_lint::{LateContext, LintContext};
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::higher::Range;
3+
use clippy_utils::is_range_full;
4+
use clippy_utils::ty::is_type_diagnostic_item;
5+
use rustc_errors::Applicability;
6+
use rustc_hir::Expr;
7+
use rustc_lint::LateContext;
8+
use rustc_span::symbol::sym;
9+
use rustc_span::Span;
210

311
use super::CLEAR_WITH_DRAIN;
412

513
// TODO: Adjust the parameters as necessary
6-
pub(super) fn check(cx: &LateContext) {
7-
todo!();
14+
// see clippy_lints/src/methods/mod.rs to add call to this check in `check_methods`
15+
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, span: Span, arg: &Expr<'_>) {
16+
let ty = cx.typeck_results().expr_ty(recv);
17+
if is_type_diagnostic_item(cx, ty, sym::Vec) && let Some(range) = Range::hir(arg) && is_range_full(cx, recv, range)
18+
{
19+
span_lint_and_sugg(
20+
cx,
21+
CLEAR_WITH_DRAIN,
22+
span.with_hi(expr.span.hi()),
23+
"`drain` used to clear a `Vec`",
24+
"try",
25+
"clear()".to_string(),
26+
Applicability::MachineApplicable,
27+
);
28+
}
829
}

clippy_lints/src/methods/mod.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ use clippy_utils::ty::{contains_ty_adt_constructor_opaque, implements_trait, is_
111111
use clippy_utils::{contains_return, is_bool, is_trait_method, iter_input_pats, return_ty};
112112
use if_chain::if_chain;
113113
use rustc_hir as hir;
114-
use rustc_hir::{Expr, ExprKind, TraitItem, TraitItemKind};
114+
use rustc_hir::{Expr, ExprKind, Node, Stmt, StmtKind, TraitItem, TraitItemKind};
115115
use rustc_hir_analysis::hir_ty_to_ty;
116116
use rustc_lint::{LateContext, LateLintPass, LintContext};
117117
use rustc_middle::lint::in_external_macro;
@@ -3590,7 +3590,13 @@ impl Methods {
35903590
_ => {},
35913591
},
35923592
("drain", [arg]) => {
3593-
iter_with_drain::check(cx, expr, recv, span, arg);
3593+
if let Node::Stmt(Stmt { hir_id: _, kind, .. }) = cx.tcx.hir().get_parent(expr.hir_id)
3594+
&& matches!(kind, StmtKind::Semi(_))
3595+
{
3596+
clear_with_drain::check(cx, expr, recv, span, arg);
3597+
} else {
3598+
iter_with_drain::check(cx, expr, recv, span, arg);
3599+
}
35943600
},
35953601
("ends_with", [arg]) => {
35963602
if let ExprKind::MethodCall(.., span) = expr.kind {

0 commit comments

Comments
 (0)