rust-clippy/clippy_lints/src/methods/bytes_nth.rs

41 lines
1.3 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
2021-03-13 23:01:03 +00:00
use clippy_utils::ty::is_type_diagnostic_item;
2021-02-07 16:34:59 +00:00
use if_chain::if_chain;
use rustc_errors::Applicability;
2021-03-11 05:40:20 +00:00
use rustc_hir::Expr;
2021-02-07 16:34:59 +00:00
use rustc_lint::LateContext;
use rustc_span::sym;
use super::BYTES_NTH;
2021-03-11 05:40:20 +00:00
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, recv: &'tcx Expr<'tcx>, n_arg: &'tcx Expr<'tcx>) {
2021-02-07 16:34:59 +00:00
if_chain! {
2021-03-11 05:40:20 +00:00
let ty = cx.typeck_results().expr_ty(recv).peel_refs();
2021-02-07 16:34:59 +00:00
let caller_type = if is_type_diagnostic_item(cx, ty, sym::string_type) {
Some("String")
} else if ty.is_str() {
Some("str")
} else {
None
};
if let Some(caller_type) = caller_type;
then {
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
BYTES_NTH,
expr.span,
&format!("called `.byte().nth()` on a `{}`", caller_type),
"try",
2021-02-07 16:34:59 +00:00
format!(
"{}.as_bytes().get({})",
2021-03-11 05:40:20 +00:00
snippet_with_applicability(cx, recv.span, "..", &mut applicability),
snippet_with_applicability(cx, n_arg.span, "..", &mut applicability)
2021-02-07 16:34:59 +00:00
),
applicability,
);
}
}
}