2 use rustc::{declare_lint, lint_array};
4 use syntax::ast::NodeId;
5 use crate::utils::{in_macro, match_def_path, match_trait_method, same_tys, snippet, span_lint_and_then};
6 use crate::utils::{opt_def_id, paths, resolve_node};
8 /// **What it does:** Checks for always-identical `Into`/`From`/`IntoIter` conversions.
10 /// **Why is this bad?** Redundant code.
12 /// **Known problems:** None.
16 /// // format!() returns a `String`
17 /// let s: String = format!("hello").into();
19 declare_clippy_lint! {
20 pub IDENTITY_CONVERSION,
22 "using always-identical `Into`/`From`/`IntoIter` conversions"
26 pub struct IdentityConversion {
27 try_desugar_arm: Vec<NodeId>,
30 impl LintPass for IdentityConversion {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(IDENTITY_CONVERSION)
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityConversion {
37 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
42 if Some(&e.id) == self.try_desugar_arm.last() {
47 ExprKind::Match(_, ref arms, MatchSource::TryDesugar) => {
48 let e = match arms[0].body.node {
49 ExprKind::Ret(Some(ref e)) | ExprKind::Break(_, Some(ref e)) => e,
52 if let ExprKind::Call(_, ref args) = e.node {
53 self.try_desugar_arm.push(args[0].id);
59 ExprKind::MethodCall(ref name, .., ref args) => {
60 if match_trait_method(cx, e, &paths::INTO[..]) && &*name.ident.as_str() == "into" {
61 let a = cx.tables.expr_ty(e);
62 let b = cx.tables.expr_ty(&args[0]);
63 if same_tys(cx, a, b) {
64 let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
65 span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
66 db.span_suggestion(e.span, "consider removing `.into()`", sugg);
70 if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" {
71 let a = cx.tables.expr_ty(e);
72 let b = cx.tables.expr_ty(&args[0]);
73 if same_tys(cx, a, b) {
74 let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
75 span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
76 db.span_suggestion(e.span, "consider removing `.into_iter()`", sugg);
82 ExprKind::Call(ref path, ref args) => if let ExprKind::Path(ref qpath) = path.node {
83 if let Some(def_id) = opt_def_id(resolve_node(cx, qpath, path.hir_id)) {
84 if match_def_path(cx.tcx, def_id, &paths::FROM_FROM[..]) {
85 let a = cx.tables.expr_ty(e);
86 let b = cx.tables.expr_ty(&args[0]);
87 if same_tys(cx, a, b) {
88 let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
89 let sugg_msg = format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
90 span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
91 db.span_suggestion(e.span, &sugg_msg, sugg);
102 fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
103 if Some(&e.id) == self.try_desugar_arm.last() {
104 self.try_desugar_arm.pop();