2 match_def_path, match_trait_method, paths, same_tys, snippet, snippet_with_macro_callsite, span_lint_and_sugg,
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind, HirId, MatchSource};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 /// **What it does:** Checks for `Into`/`From`/`IntoIter` calls that useless converts
11 /// to the same type as caller.
13 /// **Why is this bad?** Redundant code.
15 /// **Known problems:** None.
21 /// // format!() returns a `String`
22 /// let s: String = format!("hello").into();
25 /// let s: String = format!("hello");
27 pub USELESS_CONVERSION,
29 "calls to `Into`/`From`/`IntoIter` that performs useless conversions to the same type"
33 pub struct UselessConversion {
34 try_desugar_arm: Vec<HirId>,
37 impl_lint_pass!(UselessConversion => [USELESS_CONVERSION]);
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessConversion {
40 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
41 if e.span.from_expansion() {
45 if Some(&e.hir_id) == self.try_desugar_arm.last() {
50 ExprKind::Match(_, ref arms, MatchSource::TryDesugar) => {
51 let e = match arms[0].body.kind {
52 ExprKind::Ret(Some(ref e)) | ExprKind::Break(_, Some(ref e)) => e,
55 if let ExprKind::Call(_, ref args) = e.kind {
56 self.try_desugar_arm.push(args[0].hir_id);
60 ExprKind::MethodCall(ref name, .., ref args) => {
61 if match_trait_method(cx, e, &paths::INTO) && &*name.ident.as_str() == "into" {
62 let a = cx.tables.expr_ty(e);
63 let b = cx.tables.expr_ty(&args[0]);
64 if same_tys(cx, a, b) {
65 let sugg = snippet_with_macro_callsite(cx, args[0].span, "<expr>").to_string();
72 "consider removing `.into()`",
74 Applicability::MachineApplicable, // snippet
78 if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" {
79 let a = cx.tables.expr_ty(e);
80 let b = cx.tables.expr_ty(&args[0]);
81 if same_tys(cx, a, b) {
82 let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
88 "consider removing `.into_iter()`",
90 Applicability::MachineApplicable, // snippet
96 ExprKind::Call(ref path, ref args) => {
97 if let ExprKind::Path(ref qpath) = path.kind {
98 if let Some(def_id) = cx.tables.qpath_res(qpath, path.hir_id).opt_def_id() {
99 if match_def_path(cx, def_id, &paths::FROM_FROM) {
100 let a = cx.tables.expr_ty(e);
101 let b = cx.tables.expr_ty(&args[0]);
102 if same_tys(cx, a, b) {
103 let sugg = snippet(cx, args[0].span.source_callsite(), "<expr>").into_owned();
105 format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
110 "useless conversion",
113 Applicability::MachineApplicable, // snippet
125 fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
126 if Some(&e.hir_id) == self.try_desugar_arm.last() {
127 self.try_desugar_arm.pop();