]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/useless_conversion.rs
Rollup merge of #87385 - Aaron1011:final-enable-semi, r=petrochenkov
[rust.git] / clippy_lints / src / useless_conversion.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::{snippet, snippet_with_macro_callsite};
3 use clippy_utils::sugg::Sugg;
4 use clippy_utils::ty::{is_type_diagnostic_item, same_type_and_consts};
5 use clippy_utils::{get_parent_expr, is_trait_method, match_def_path, paths};
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;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls
17     /// which uselessly convert to the same type.
18     ///
19     /// ### Why is this bad?
20     /// Redundant code.
21     ///
22     /// ### Example
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`, or `IntoIter` which perform 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(_, arms, MatchSource::TryDesugar) => {
56                 let e = match arms[0].body.kind {
57                     ExprKind::Ret(Some(e)) | ExprKind::Break(_, Some(e)) => e,
58                     _ => return,
59                 };
60                 if let ExprKind::Call(_, args) = e.kind {
61                     self.try_desugar_arm.push(args[0].hir_id);
62                 }
63             },
64
65             ExprKind::MethodCall(name, .., args, _) => {
66                 if is_trait_method(cx, e, sym::into_trait) && &*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 same_type_and_consts(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                             &format!("useless conversion to the same type: `{}`", b),
76                             "consider removing `.into()`",
77                             sugg,
78                             Applicability::MachineApplicable, // snippet
79                         );
80                     }
81                 }
82                 if is_trait_method(cx, e, sym::IntoIterator) && name.ident.name == sym::into_iter {
83                     if let Some(parent_expr) = get_parent_expr(cx, e) {
84                         if let ExprKind::MethodCall(parent_name, ..) = parent_expr.kind {
85                             if parent_name.ident.name != sym::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 same_type_and_consts(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                             &format!("useless conversion to the same type: `{}`", b),
99                             "consider removing `.into_iter()`",
100                             sugg,
101                             Applicability::MachineApplicable, // snippet
102                         );
103                     }
104                 }
105                 if_chain! {
106                     if is_trait_method(cx, e, sym::try_into_trait) && name.ident.name == sym::try_into;
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 same_type_and_consts(a_type, b);
113
114                     then {
115                         span_lint_and_help(
116                             cx,
117                             USELESS_CONVERSION,
118                             e.span,
119                             &format!("useless conversion to the same type: `{}`", b),
120                             None,
121                             "consider removing `.try_into()`",
122                         );
123                     }
124                 }
125             },
126
127             ExprKind::Call(path, args) => {
128                 if_chain! {
129                     if args.len() == 1;
130                     if let ExprKind::Path(ref qpath) = path.kind;
131                     if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
132                     then {
133                         let a = cx.typeck_results().expr_ty(e);
134                         let b = cx.typeck_results().expr_ty(&args[0]);
135                         if_chain! {
136                             if match_def_path(cx, def_id, &paths::TRY_FROM);
137                             if is_type_diagnostic_item(cx, a, sym::result_type);
138                             if let ty::Adt(_, substs) = a.kind();
139                             if let Some(a_type) = substs.types().next();
140                             if same_type_and_consts(a_type, b);
141
142                             then {
143                                 let hint = format!("consider removing `{}()`", snippet(cx, path.span, "TryFrom::try_from"));
144                                 span_lint_and_help(
145                                     cx,
146                                     USELESS_CONVERSION,
147                                     e.span,
148                                     &format!("useless conversion to the same type: `{}`", b),
149                                     None,
150                                     &hint,
151                                 );
152                             }
153                         }
154
155                         if_chain! {
156                             if match_def_path(cx, def_id, &paths::FROM_FROM);
157                             if same_type_and_consts(a, b);
158
159                             then {
160                                 let sugg = Sugg::hir_with_macro_callsite(cx, &args[0], "<expr>").maybe_par();
161                                 let sugg_msg =
162                                     format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
163                                 span_lint_and_sugg(
164                                     cx,
165                                     USELESS_CONVERSION,
166                                     e.span,
167                                     &format!("useless conversion to the same type: `{}`", b),
168                                     &sugg_msg,
169                                     sugg.to_string(),
170                                     Applicability::MachineApplicable, // snippet
171                                 );
172                             }
173                         }
174                     }
175                 }
176             },
177
178             _ => {},
179         }
180     }
181
182     fn check_expr_post(&mut self, _: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
183         if Some(&e.hir_id) == self.try_desugar_arm.last() {
184             self.try_desugar_arm.pop();
185         }
186     }
187 }