]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/useless_conversion.rs
Auto merge of #6828 - mgacek8:issue_6758_enhance_wrong_self_convention, r=flip1995
[rust.git] / clippy_lints / src / useless_conversion.rs
1 use crate::utils::sugg::Sugg;
2 use crate::utils::{
3     get_parent_expr, match_def_path, match_trait_method, paths, snippet, snippet_with_macro_callsite,
4     span_lint_and_help, span_lint_and_sugg,
5 };
6 use clippy_utils::ty::is_type_diagnostic_item;
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::{Expr, ExprKind, HirId, MatchSource};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{self, TyS};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::sym;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls
17     /// which uselessly convert to the same type.
18     ///
19     /// **Why is this bad?** Redundant code.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     ///
25     /// ```rust
26     /// // Bad
27     /// // format!() returns a `String`
28     /// let s: String = format!("hello").into();
29     ///
30     /// // Good
31     /// let s: String = format!("hello");
32     /// ```
33     pub USELESS_CONVERSION,
34     complexity,
35     "calls to `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` which perform useless conversions to the same type"
36 }
37
38 #[derive(Default)]
39 pub struct UselessConversion {
40     try_desugar_arm: Vec<HirId>,
41 }
42
43 impl_lint_pass!(UselessConversion => [USELESS_CONVERSION]);
44
45 #[allow(clippy::too_many_lines)]
46 impl<'tcx> LateLintPass<'tcx> for UselessConversion {
47     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
48         if e.span.from_expansion() {
49             return;
50         }
51
52         if Some(&e.hir_id) == self.try_desugar_arm.last() {
53             return;
54         }
55
56         match e.kind {
57             ExprKind::Match(_, ref arms, MatchSource::TryDesugar) => {
58                 let e = match arms[0].body.kind {
59                     ExprKind::Ret(Some(ref e)) | ExprKind::Break(_, Some(ref e)) => e,
60                     _ => return,
61                 };
62                 if let ExprKind::Call(_, ref args) = e.kind {
63                     self.try_desugar_arm.push(args[0].hir_id);
64                 }
65             },
66
67             ExprKind::MethodCall(ref name, .., ref args, _) => {
68                 if match_trait_method(cx, e, &paths::INTO) && &*name.ident.as_str() == "into" {
69                     let a = cx.typeck_results().expr_ty(e);
70                     let b = cx.typeck_results().expr_ty(&args[0]);
71                     if TyS::same_type(a, b) {
72                         let sugg = snippet_with_macro_callsite(cx, args[0].span, "<expr>").to_string();
73                         span_lint_and_sugg(
74                             cx,
75                             USELESS_CONVERSION,
76                             e.span,
77                             &format!("useless conversion to the same type: `{}`", b),
78                             "consider removing `.into()`",
79                             sugg,
80                             Applicability::MachineApplicable, // snippet
81                         );
82                     }
83                 }
84                 if match_trait_method(cx, e, &paths::INTO_ITERATOR) && name.ident.name == sym::into_iter {
85                     if let Some(parent_expr) = get_parent_expr(cx, e) {
86                         if let ExprKind::MethodCall(ref parent_name, ..) = parent_expr.kind {
87                             if parent_name.ident.name != sym::into_iter {
88                                 return;
89                             }
90                         }
91                     }
92                     let a = cx.typeck_results().expr_ty(e);
93                     let b = cx.typeck_results().expr_ty(&args[0]);
94                     if TyS::same_type(a, b) {
95                         let sugg = snippet(cx, args[0].span, "<expr>").into_owned();
96                         span_lint_and_sugg(
97                             cx,
98                             USELESS_CONVERSION,
99                             e.span,
100                             &format!("useless conversion to the same type: `{}`", b),
101                             "consider removing `.into_iter()`",
102                             sugg,
103                             Applicability::MachineApplicable, // snippet
104                         );
105                     }
106                 }
107                 if match_trait_method(cx, e, &paths::TRY_INTO_TRAIT) && &*name.ident.as_str() == "try_into" {
108                     if_chain! {
109                         let a = cx.typeck_results().expr_ty(e);
110                         let b = cx.typeck_results().expr_ty(&args[0]);
111                         if is_type_diagnostic_item(cx, a, sym::result_type);
112                         if let ty::Adt(_, substs) = a.kind();
113                         if let Some(a_type) = substs.types().next();
114                         if TyS::same_type(a_type, b);
115
116                         then {
117                             span_lint_and_help(
118                                 cx,
119                                 USELESS_CONVERSION,
120                                 e.span,
121                                 &format!("useless conversion to the same type: `{}`", b),
122                                 None,
123                                 "consider removing `.try_into()`",
124                             );
125                         }
126                     }
127                 }
128             },
129
130             ExprKind::Call(ref path, ref args) => {
131                 if_chain! {
132                     if args.len() == 1;
133                     if let ExprKind::Path(ref qpath) = path.kind;
134                     if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
135                     let a = cx.typeck_results().expr_ty(e);
136                     let b = cx.typeck_results().expr_ty(&args[0]);
137
138                     then {
139                         if_chain! {
140                             if match_def_path(cx, def_id, &paths::TRY_FROM);
141                             if is_type_diagnostic_item(cx, a, sym::result_type);
142                             if let ty::Adt(_, substs) = a.kind();
143                             if let Some(a_type) = substs.types().next();
144                             if TyS::same_type(a_type, b);
145
146                             then {
147                                 let hint = format!("consider removing `{}()`", snippet(cx, path.span, "TryFrom::try_from"));
148                                 span_lint_and_help(
149                                     cx,
150                                     USELESS_CONVERSION,
151                                     e.span,
152                                     &format!("useless conversion to the same type: `{}`", b),
153                                     None,
154                                     &hint,
155                                 );
156                             }
157                         }
158
159                         if_chain! {
160                             if match_def_path(cx, def_id, &paths::FROM_FROM);
161                             if TyS::same_type(a, b);
162
163                             then {
164                                 let sugg = Sugg::hir_with_macro_callsite(cx, &args[0], "<expr>").maybe_par();
165                                 let sugg_msg =
166                                     format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
167                                 span_lint_and_sugg(
168                                     cx,
169                                     USELESS_CONVERSION,
170                                     e.span,
171                                     &format!("useless conversion to the same type: `{}`", b),
172                                     &sugg_msg,
173                                     sugg.to_string(),
174                                     Applicability::MachineApplicable, // snippet
175                                 );
176                             }
177                         }
178                     }
179                 }
180             },
181
182             _ => {},
183         }
184     }
185
186     fn check_expr_post(&mut self, _: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
187         if Some(&e.hir_id) == self.try_desugar_arm.last() {
188             self.try_desugar_arm.pop();
189         }
190     }
191 }