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 always-identical `Into`/`From`/`IntoIter` conversions.
12 /// **Why is this bad?** Redundant code.
14 /// **Known problems:** None.
18 /// // format!() returns a `String`
19 /// let s: String = format!("hello").into();
21 pub IDENTITY_CONVERSION,
23 "using always-identical `Into`/`From`/`IntoIter` conversions"
27 pub struct IdentityConversion {
28 try_desugar_arm: Vec<HirId>,
31 impl_lint_pass!(IdentityConversion => [IDENTITY_CONVERSION]);
33 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityConversion {
34 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
35 if e.span.from_expansion() {
39 if Some(&e.hir_id) == self.try_desugar_arm.last() {
44 ExprKind::Match(_, ref arms, MatchSource::TryDesugar) => {
45 let e = match arms[0].body.kind {
46 ExprKind::Ret(Some(ref e)) | ExprKind::Break(_, Some(ref e)) => e,
49 if let ExprKind::Call(_, ref args) = e.kind {
50 self.try_desugar_arm.push(args[0].hir_id);
54 ExprKind::MethodCall(ref name, .., ref args) => {
55 if match_trait_method(cx, e, &paths::INTO) && &*name.ident.as_str() == "into" {
56 let a = cx.tables.expr_ty(e);
57 let b = cx.tables.expr_ty(&args[0]);
58 if same_tys(cx, a, b) {
59 let sugg = snippet_with_macro_callsite(cx, args[0].span, "<expr>").to_string();
65 "identical conversion",
66 "consider removing `.into()`",
68 Applicability::MachineApplicable, // snippet
72 if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" {
73 let a = cx.tables.expr_ty(e);
74 let b = cx.tables.expr_ty(&args[0]);
75 if same_tys(cx, a, b) {
76 let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
81 "identical conversion",
82 "consider removing `.into_iter()`",
84 Applicability::MachineApplicable, // snippet
90 ExprKind::Call(ref path, ref args) => {
91 if let ExprKind::Path(ref qpath) = path.kind {
92 if let Some(def_id) = cx.tables.qpath_res(qpath, path.hir_id).opt_def_id() {
93 if match_def_path(cx, def_id, &paths::FROM_FROM) {
94 let a = cx.tables.expr_ty(e);
95 let b = cx.tables.expr_ty(&args[0]);
96 if same_tys(cx, a, b) {
97 let sugg = snippet(cx, args[0].span.source_callsite(), "<expr>").into_owned();
99 format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
104 "identical conversion",
107 Applicability::MachineApplicable, // snippet
119 fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
120 if Some(&e.hir_id) == self.try_desugar_arm.last() {
121 self.try_desugar_arm.pop();