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