2021-03-16 00:55:45 +00:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_sugg;
|
2021-03-13 23:01:03 +00:00
|
|
|
use clippy_utils::ty::has_iter_method;
|
2021-03-16 16:06:34 +00:00
|
|
|
use clippy_utils::{match_trait_method, paths};
|
2021-03-17 05:14:06 +00:00
|
|
|
use if_chain::if_chain;
|
2021-03-06 08:28:14 +00:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_lint::LateContext;
|
|
|
|
use rustc_middle::ty::{self, Ty};
|
|
|
|
use rustc_span::source_map::Span;
|
2021-03-17 05:14:06 +00:00
|
|
|
use rustc_span::symbol::{sym, Symbol};
|
2021-03-06 08:28:14 +00:00
|
|
|
|
|
|
|
use super::INTO_ITER_ON_REF;
|
|
|
|
|
2021-03-17 05:14:06 +00:00
|
|
|
pub(super) fn check(
|
|
|
|
cx: &LateContext<'_>,
|
|
|
|
expr: &hir::Expr<'_>,
|
|
|
|
method_span: Span,
|
|
|
|
method_name: Symbol,
|
|
|
|
args: &[hir::Expr<'_>],
|
|
|
|
) {
|
|
|
|
let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
|
|
|
|
if_chain! {
|
|
|
|
if let ty::Ref(..) = self_ty.kind();
|
|
|
|
if method_name == sym::into_iter;
|
|
|
|
if match_trait_method(cx, expr, &paths::INTO_ITERATOR);
|
|
|
|
if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ty);
|
|
|
|
then {
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
INTO_ITER_ON_REF,
|
|
|
|
method_span,
|
|
|
|
&format!(
|
|
|
|
"this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
|
|
|
|
method_name, kind,
|
|
|
|
),
|
|
|
|
"call directly",
|
|
|
|
method_name.to_string(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
2021-03-06 08:28:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 11:02:29 +00:00
|
|
|
fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(Symbol, &'static str)> {
|
2021-03-06 08:28:14 +00:00
|
|
|
has_iter_method(cx, self_ref_ty).map(|ty_name| {
|
|
|
|
let mutbl = match self_ref_ty.kind() {
|
|
|
|
ty::Ref(_, _, mutbl) => mutbl,
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
let method_name = match mutbl {
|
|
|
|
hir::Mutability::Not => "iter",
|
|
|
|
hir::Mutability::Mut => "iter_mut",
|
|
|
|
};
|
|
|
|
(ty_name, method_name)
|
|
|
|
})
|
|
|
|
}
|