rust/clippy_lints/src/methods/needless_as_bytes.rs
Quentin Santos d5264c7a46 Check for needless uses of str::bytes()
This builds upon the lint for `str::as_bytes()`, and also covers
needless uses of the iterator version `str::bytes()`.
2025-01-09 18:44:43 +01:00

26 lines
962 B
Rust

use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::is_type_lang_item;
use rustc_errors::Applicability;
use rustc_hir::{Expr, LangItem};
use rustc_lint::LateContext;
use rustc_span::Span;
use super::NEEDLESS_AS_BYTES;
pub fn check(cx: &LateContext<'_>, prev_method: &str, method: &str, prev_recv: &Expr<'_>, span: Span) {
let ty1 = cx.typeck_results().expr_ty_adjusted(prev_recv).peel_refs();
if is_type_lang_item(cx, ty1, LangItem::String) || ty1.is_str() {
let mut app = Applicability::MachineApplicable;
let sugg = Sugg::hir_with_context(cx, prev_recv, span.ctxt(), "..", &mut app);
span_lint_and_sugg(
cx,
NEEDLESS_AS_BYTES,
span,
format!("needless call to `{prev_method}`"),
format!("`{method}()` can be called directly on strings"),
format!("{sugg}.{method}()"),
app,
);
}
}