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