]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/identity_conversion.rs
Merge remote-tracking branch 'upstream/master'
[rust.git] / clippy_lints / src / identity_conversion.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc::hir::*;
14 use crate::syntax::ast::NodeId;
15 use crate::utils::{in_macro, match_def_path, match_trait_method, same_tys, snippet, snippet_with_macro_callsite, span_lint_and_then};
16 use crate::utils::{opt_def_id, paths, resolve_node};
17 use crate::rustc_errors::Applicability;
18
19 /// **What it does:** Checks for always-identical `Into`/`From`/`IntoIter` conversions.
20 ///
21 /// **Why is this bad?** Redundant code.
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// // format!() returns a `String`
28 /// let s: String = format!("hello").into();
29 /// ```
30 declare_clippy_lint! {
31     pub IDENTITY_CONVERSION,
32     complexity,
33     "using always-identical `Into`/`From`/`IntoIter` conversions"
34 }
35
36 #[derive(Default)]
37 pub struct IdentityConversion {
38     try_desugar_arm: Vec<NodeId>,
39 }
40
41 impl LintPass for IdentityConversion {
42     fn get_lints(&self) -> LintArray {
43         lint_array!(IDENTITY_CONVERSION)
44     }
45 }
46
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityConversion {
48     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
49         if in_macro(e.span) {
50             return;
51         }
52
53         if Some(&e.id) == self.try_desugar_arm.last() {
54             return;
55         }
56
57         match e.node {
58             ExprKind::Match(_, ref arms, MatchSource::TryDesugar) => {
59                 let e = match arms[0].body.node {
60                     ExprKind::Ret(Some(ref e)) | ExprKind::Break(_, Some(ref e)) => e,
61                     _ => return,
62                 };
63                 if let ExprKind::Call(_, ref args) = e.node {
64                     self.try_desugar_arm.push(args[0].id);
65                 } else {
66                     return;
67                 }
68             },
69
70             ExprKind::MethodCall(ref name, .., ref args) => {
71                 if match_trait_method(cx, e, &paths::INTO[..]) && &*name.ident.as_str() == "into" {
72                     let a = cx.tables.expr_ty(e);
73                     let b = cx.tables.expr_ty(&args[0]);
74                     if same_tys(cx, a, b) {
75                         let sugg = snippet_with_macro_callsite(cx, args[0].span, "<expr>").to_string();
76
77                         span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
78                             db.span_suggestion_with_applicability(
79                                 e.span,
80                                 "consider removing `.into()`",
81                                 sugg,
82                                 Applicability::MachineApplicable, // snippet
83                             );
84                         });
85                     }
86                 }
87                 if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" {
88                     let a = cx.tables.expr_ty(e);
89                     let b = cx.tables.expr_ty(&args[0]);
90                     if same_tys(cx, a, b) {
91                         let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
92                         span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
93                             db.span_suggestion_with_applicability(
94                                 e.span,
95                                 "consider removing `.into_iter()`",
96                                 sugg,
97                                 Applicability::MachineApplicable, // snippet
98                             );
99                         });
100                     }
101                 }
102             },
103
104             ExprKind::Call(ref path, ref args) => if let ExprKind::Path(ref qpath) = path.node {
105                 if let Some(def_id) = opt_def_id(resolve_node(cx, qpath, path.hir_id)) {
106                     if match_def_path(cx.tcx, def_id, &paths::FROM_FROM[..]) {
107                         let a = cx.tables.expr_ty(e);
108                         let b = cx.tables.expr_ty(&args[0]);
109                         if same_tys(cx, a, b) {
110                             let sugg = snippet(cx, args[0].span.source_callsite(), "<expr>").into_owned();
111                             let sugg_msg = format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
112                             span_lint_and_then(cx, IDENTITY_CONVERSION, e.span, "identical conversion", |db| {
113                                 db.span_suggestion_with_applicability(
114                                     e.span,
115                                     &sugg_msg,
116                                     sugg,
117                                     Applicability::MachineApplicable, // snippet
118                                 );
119                             });
120                         }
121                     }
122                 }
123             },
124
125             _ => {},
126         }
127     }
128
129     fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
130         if Some(&e.id) == self.try_desugar_arm.last() {
131             self.try_desugar_arm.pop();
132         }
133     }
134 }