rust-clippy/clippy_lints/src/useless_conversion.rs

189 lines
7.8 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
use clippy_utils::source::{snippet, snippet_with_macro_callsite};
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::{is_type_diagnostic_item, same_type_and_consts};
use clippy_utils::{get_parent_expr, is_trait_method, match_def_path, paths};
use if_chain::if_chain;
use rustc_errors::Applicability;
2020-02-21 08:39:38 +00:00
use rustc_hir::{Expr, ExprKind, HirId, MatchSource};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::sym;
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls
/// which uselessly convert to the same type.
///
/// ### Why is this bad?
/// Redundant code.
///
/// ### Example
/// ```rust
/// // Bad
/// // format!() returns a `String`
/// let s: String = format!("hello").into();
///
/// // Good
/// let s: String = format!("hello");
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 19:06:26 +00:00
#[clippy::version = "1.45.0"]
pub USELESS_CONVERSION,
2018-03-28 13:24:26 +00:00
complexity,
"calls to `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` which perform useless conversions to the same type"
}
#[derive(Default)]
pub struct UselessConversion {
2019-02-24 18:43:15 +00:00
try_desugar_arm: Vec<HirId>,
}
impl_lint_pass!(UselessConversion => [USELESS_CONVERSION]);
#[allow(clippy::too_many_lines)]
impl<'tcx> LateLintPass<'tcx> for UselessConversion {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
2019-08-19 16:30:32 +00:00
if e.span.from_expansion() {
return;
}
2019-02-24 18:43:15 +00:00
if Some(&e.hir_id) == self.try_desugar_arm.last() {
return;
}
2019-09-27 15:16:06 +00:00
match e.kind {
ExprKind::Match(_, arms, MatchSource::TryDesugar) => {
2019-09-27 15:16:06 +00:00
let e = match arms[0].body.kind {
ExprKind::Ret(Some(e)) | ExprKind::Break(_, Some(e)) => e,
_ => return,
};
if let ExprKind::Call(_, args) = e.kind {
2019-02-24 18:43:15 +00:00
self.try_desugar_arm.push(args[0].hir_id);
}
},
ExprKind::MethodCall(name, .., args, _) => {
2021-10-02 23:51:01 +00:00
if is_trait_method(cx, e, sym::Into) && &*name.ident.as_str() == "into" {
2020-07-17 08:47:04 +00:00
let a = cx.typeck_results().expr_ty(e);
let b = cx.typeck_results().expr_ty(&args[0]);
if same_type_and_consts(a, b) {
let sugg = snippet_with_macro_callsite(cx, args[0].span, "<expr>").to_string();
span_lint_and_sugg(
cx,
USELESS_CONVERSION,
e.span,
&format!("useless conversion to the same type: `{}`", b),
"consider removing `.into()`",
sugg,
Applicability::MachineApplicable, // snippet
);
}
}
if is_trait_method(cx, e, sym::IntoIterator) && name.ident.name == sym::into_iter {
if let Some(parent_expr) = get_parent_expr(cx, e) {
if let ExprKind::MethodCall(parent_name, ..) = parent_expr.kind {
if parent_name.ident.name != sym::into_iter {
return;
}
}
}
2020-07-17 08:47:04 +00:00
let a = cx.typeck_results().expr_ty(e);
let b = cx.typeck_results().expr_ty(&args[0]);
if same_type_and_consts(a, b) {
let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
span_lint_and_sugg(
cx,
USELESS_CONVERSION,
e.span,
&format!("useless conversion to the same type: `{}`", b),
"consider removing `.into_iter()`",
sugg,
Applicability::MachineApplicable, // snippet
);
}
}
if_chain! {
2021-10-02 23:51:01 +00:00
if is_trait_method(cx, e, sym::TryInto) && name.ident.name == sym::try_into;
let a = cx.typeck_results().expr_ty(e);
let b = cx.typeck_results().expr_ty(&args[0]);
2021-10-02 23:51:01 +00:00
if is_type_diagnostic_item(cx, a, sym::Result);
if let ty::Adt(_, substs) = a.kind();
if let Some(a_type) = substs.types().next();
if same_type_and_consts(a_type, b);
then {
span_lint_and_help(
cx,
USELESS_CONVERSION,
e.span,
&format!("useless conversion to the same type: `{}`", b),
None,
"consider removing `.try_into()`",
);
}
}
},
ExprKind::Call(path, args) => {
if_chain! {
if args.len() == 1;
if let ExprKind::Path(ref qpath) = path.kind;
if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
then {
let a = cx.typeck_results().expr_ty(e);
let b = cx.typeck_results().expr_ty(&args[0]);
if_chain! {
if match_def_path(cx, def_id, &paths::TRY_FROM);
2021-10-02 23:51:01 +00:00
if is_type_diagnostic_item(cx, a, sym::Result);
if let ty::Adt(_, substs) = a.kind();
if let Some(a_type) = substs.types().next();
if same_type_and_consts(a_type, b);
then {
let hint = format!("consider removing `{}()`", snippet(cx, path.span, "TryFrom::try_from"));
span_lint_and_help(
cx,
USELESS_CONVERSION,
e.span,
&format!("useless conversion to the same type: `{}`", b),
None,
&hint,
);
}
}
if_chain! {
if match_def_path(cx, def_id, &paths::FROM_FROM);
if same_type_and_consts(a, b);
then {
let sugg = Sugg::hir_with_macro_callsite(cx, &args[0], "<expr>").maybe_par();
2018-11-27 20:14:15 +00:00
let sugg_msg =
format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
span_lint_and_sugg(
cx,
USELESS_CONVERSION,
e.span,
&format!("useless conversion to the same type: `{}`", b),
&sugg_msg,
sugg.to_string(),
Applicability::MachineApplicable, // snippet
);
2018-11-27 20:14:15 +00:00
}
}
}
}
},
_ => {},
}
}
fn check_expr_post(&mut self, _: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
2019-02-24 18:43:15 +00:00
if Some(&e.hir_id) == self.try_desugar_arm.last() {
self.try_desugar_arm.pop();
}
}
}