]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/useless_conversion.rs
Rollup merge of #106260 - chenyukang:yukang/fix-106213-doc, r=GuillaumeGomez
[rust.git] / src / tools / clippy / 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_copy, is_type_diagnostic_item, same_type_and_consts};
5 use clippy_utils::{get_parent_expr, is_trait_method, match_def_path, path_to_local, paths};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BindingAnnotation, Expr, ExprKind, HirId, MatchSource, Node, PatKind};
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     /// // format!() returns a `String`
25     /// let s: String = format!("hello").into();
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// let s: String = format!("hello");
31     /// ```
32     #[clippy::version = "1.45.0"]
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 #[expect(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(_, arms, MatchSource::TryDesugar) => {
58                 let (ExprKind::Ret(Some(e)) | ExprKind::Break(_, Some(e))) = arms[0].body.kind else {
59                      return
60                 };
61                 if let ExprKind::Call(_, [arg, ..]) = e.kind {
62                     self.try_desugar_arm.push(arg.hir_id);
63                 }
64             },
65
66             ExprKind::MethodCall(name, recv, ..) => {
67                 if is_trait_method(cx, e, sym::Into) && name.ident.as_str() == "into" {
68                     let a = cx.typeck_results().expr_ty(e);
69                     let b = cx.typeck_results().expr_ty(recv);
70                     if same_type_and_consts(a, b) {
71                         let sugg = snippet_with_macro_callsite(cx, recv.span, "<expr>").to_string();
72                         span_lint_and_sugg(
73                             cx,
74                             USELESS_CONVERSION,
75                             e.span,
76                             &format!("useless conversion to the same type: `{b}`"),
77                             "consider removing `.into()`",
78                             sugg,
79                             Applicability::MachineApplicable, // snippet
80                         );
81                     }
82                 }
83                 if is_trait_method(cx, e, sym::IntoIterator) && name.ident.name == sym::into_iter {
84                     if get_parent_expr(cx, e).is_some() &&
85                        let Some(id) = path_to_local(recv) &&
86                        let Node::Pat(pat) = cx.tcx.hir().get(id) &&
87                        let PatKind::Binding(ann, ..) = pat.kind &&
88                        ann != BindingAnnotation::MUT
89                     {
90                         // Do not remove .into_iter() applied to a non-mutable local variable used in
91                         // a larger expression context as it would differ in mutability.
92                         return;
93                     }
94
95                     let a = cx.typeck_results().expr_ty(e);
96                     let b = cx.typeck_results().expr_ty(recv);
97
98                     // If the types are identical then .into_iter() can be removed, unless the type
99                     // implements Copy, in which case .into_iter() returns a copy of the receiver and
100                     // cannot be safely omitted.
101                     if same_type_and_consts(a, b) && !is_copy(cx, b) {
102                         let sugg = snippet(cx, recv.span, "<expr>").into_owned();
103                         span_lint_and_sugg(
104                             cx,
105                             USELESS_CONVERSION,
106                             e.span,
107                             &format!("useless conversion to the same type: `{b}`"),
108                             "consider removing `.into_iter()`",
109                             sugg,
110                             Applicability::MachineApplicable, // snippet
111                         );
112                     }
113                 }
114                 if_chain! {
115                     if is_trait_method(cx, e, sym::TryInto) && name.ident.name == sym::try_into;
116                     let a = cx.typeck_results().expr_ty(e);
117                     let b = cx.typeck_results().expr_ty(recv);
118                     if is_type_diagnostic_item(cx, a, sym::Result);
119                     if let ty::Adt(_, substs) = a.kind();
120                     if let Some(a_type) = substs.types().next();
121                     if same_type_and_consts(a_type, b);
122
123                     then {
124                         span_lint_and_help(
125                             cx,
126                             USELESS_CONVERSION,
127                             e.span,
128                             &format!("useless conversion to the same type: `{b}`"),
129                             None,
130                             "consider removing `.try_into()`",
131                         );
132                     }
133                 }
134             },
135
136             ExprKind::Call(path, [arg]) => {
137                 if_chain! {
138                     if let ExprKind::Path(ref qpath) = path.kind;
139                     if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
140                     then {
141                         let a = cx.typeck_results().expr_ty(e);
142                         let b = cx.typeck_results().expr_ty(arg);
143                         if_chain! {
144                             if match_def_path(cx, def_id, &paths::TRY_FROM);
145                             if is_type_diagnostic_item(cx, a, sym::Result);
146                             if let ty::Adt(_, substs) = a.kind();
147                             if let Some(a_type) = substs.types().next();
148                             if same_type_and_consts(a_type, b);
149
150                             then {
151                                 let hint = format!("consider removing `{}()`", snippet(cx, path.span, "TryFrom::try_from"));
152                                 span_lint_and_help(
153                                     cx,
154                                     USELESS_CONVERSION,
155                                     e.span,
156                                     &format!("useless conversion to the same type: `{b}`"),
157                                     None,
158                                     &hint,
159                                 );
160                             }
161                         }
162
163                         if_chain! {
164                             if Some(def_id) == cx.tcx.lang_items().from_fn();
165                             if same_type_and_consts(a, b);
166
167                             then {
168                                 let sugg = Sugg::hir_with_macro_callsite(cx, arg, "<expr>").maybe_par();
169                                 let sugg_msg =
170                                     format!("consider removing `{}()`", snippet(cx, path.span, "From::from"));
171                                 span_lint_and_sugg(
172                                     cx,
173                                     USELESS_CONVERSION,
174                                     e.span,
175                                     &format!("useless conversion to the same type: `{b}`"),
176                                     &sugg_msg,
177                                     sugg.to_string(),
178                                     Applicability::MachineApplicable, // snippet
179                                 );
180                             }
181                         }
182                     }
183                 }
184             },
185
186             _ => {},
187         }
188     }
189
190     fn check_expr_post(&mut self, _: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
191         if Some(&e.hir_id) == self.try_desugar_arm.last() {
192             self.try_desugar_arm.pop();
193         }
194     }
195 }