]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs
Rollup merge of #88300 - ijackson:exitstatusext-methods, r=yaahc
[rust.git] / src / tools / clippy / clippy_lints / src / unnecessary_sort_by.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind, Mutability, Param, Pat, PatKind, Path, PathSegment, QPath};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::{self, subst::GenericArgKind};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
11 use rustc_span::symbol::Ident;
12 use std::iter;
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Detects uses of `Vec::sort_by` passing in a closure
17     /// which compares the two arguments, either directly or indirectly.
18     ///
19     /// ### Why is this bad?
20     /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
21     /// possible) than to use `Vec::sort_by` and a more complicated
22     /// closure.
23     ///
24     /// ### Known problems
25     /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
26     /// imported by a use statement, then it will need to be added manually.
27     ///
28     /// ### Example
29     /// ```rust
30     /// # struct A;
31     /// # impl A { fn foo(&self) {} }
32     /// # let mut vec: Vec<A> = Vec::new();
33     /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
34     /// ```
35     /// Use instead:
36     /// ```rust
37     /// # struct A;
38     /// # impl A { fn foo(&self) {} }
39     /// # let mut vec: Vec<A> = Vec::new();
40     /// vec.sort_by_key(|a| a.foo());
41     /// ```
42     pub UNNECESSARY_SORT_BY,
43     complexity,
44     "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
45 }
46
47 declare_lint_pass!(UnnecessarySortBy => [UNNECESSARY_SORT_BY]);
48
49 enum LintTrigger {
50     Sort(SortDetection),
51     SortByKey(SortByKeyDetection),
52 }
53
54 struct SortDetection {
55     vec_name: String,
56     unstable: bool,
57 }
58
59 struct SortByKeyDetection {
60     vec_name: String,
61     closure_arg: String,
62     closure_body: String,
63     reverse: bool,
64     unstable: bool,
65 }
66
67 /// Detect if the two expressions are mirrored (identical, except one
68 /// contains a and the other replaces it with b)
69 fn mirrored_exprs(
70     cx: &LateContext<'_>,
71     a_expr: &Expr<'_>,
72     a_ident: &Ident,
73     b_expr: &Expr<'_>,
74     b_ident: &Ident,
75 ) -> bool {
76     match (&a_expr.kind, &b_expr.kind) {
77         // Two boxes with mirrored contents
78         (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => {
79             mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
80         },
81         // Two arrays with mirrored contents
82         (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => {
83             iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
84         },
85         // The two exprs are function calls.
86         // Check to see that the function itself and its arguments are mirrored
87         (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
88             mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
89                 && iter::zip(*left_args, *right_args)
90                     .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
91         },
92         // The two exprs are method calls.
93         // Check to see that the function is the same and the arguments are mirrored
94         // This is enough because the receiver of the method is listed in the arguments
95         (
96             ExprKind::MethodCall(left_segment, _, left_args, _),
97             ExprKind::MethodCall(right_segment, _, right_args, _),
98         ) => {
99             left_segment.ident == right_segment.ident
100                 && iter::zip(*left_args, *right_args)
101                     .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
102         },
103         // Two tuples with mirrored contents
104         (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => {
105             iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
106         },
107         // Two binary ops, which are the same operation and which have mirrored arguments
108         (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
109             left_op.node == right_op.node
110                 && mirrored_exprs(cx, left_left, a_ident, right_left, b_ident)
111                 && mirrored_exprs(cx, left_right, a_ident, right_right, b_ident)
112         },
113         // Two unary ops, which are the same operation and which have the same argument
114         (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
115             left_op == right_op && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
116         },
117         // The two exprs are literals of some kind
118         (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
119         (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(cx, left, a_ident, right, b_ident),
120         (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
121             mirrored_exprs(cx, left_block, a_ident, right_block, b_ident)
122         },
123         (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
124             left_ident.name == right_ident.name && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident)
125         },
126         // Two paths: either one is a and the other is b, or they're identical to each other
127         (
128             ExprKind::Path(QPath::Resolved(
129                 _,
130                 Path {
131                     segments: left_segments,
132                     ..
133                 },
134             )),
135             ExprKind::Path(QPath::Resolved(
136                 _,
137                 Path {
138                     segments: right_segments,
139                     ..
140                 },
141             )),
142         ) => {
143             (iter::zip(*left_segments, *right_segments).all(|(left, right)| left.ident == right.ident)
144                 && left_segments
145                     .iter()
146                     .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
147                 || (left_segments.len() == 1
148                     && &left_segments[0].ident == a_ident
149                     && right_segments.len() == 1
150                     && &right_segments[0].ident == b_ident)
151         },
152         // Matching expressions, but one or both is borrowed
153         (
154             ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
155             ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
156         ) => left_kind == right_kind && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident),
157         (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => {
158             mirrored_exprs(cx, a_expr, a_ident, right_expr, b_ident)
159         },
160         (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident),
161         _ => false,
162     }
163 }
164
165 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintTrigger> {
166     if_chain! {
167         if let ExprKind::MethodCall(name_ident, _, args, _) = &expr.kind;
168         if let name = name_ident.ident.name.to_ident_string();
169         if name == "sort_by" || name == "sort_unstable_by";
170         if let [vec, Expr { kind: ExprKind::Closure(_, _, closure_body_id, _, _), .. }] = args;
171         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(vec), sym::Vec);
172         if let closure_body = cx.tcx.hir().body(*closure_body_id);
173         if let &[
174             Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
175             Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
176         ] = &closure_body.params;
177         if let ExprKind::MethodCall(method_path, _, [ref left_expr, ref right_expr], _) = &closure_body.value.kind;
178         if method_path.ident.name == sym::cmp;
179         then {
180             let (closure_body, closure_arg, reverse) = if mirrored_exprs(
181                 cx,
182                 left_expr,
183                 left_ident,
184                 right_expr,
185                 right_ident
186             ) {
187                 (Sugg::hir(cx, left_expr, "..").to_string(), left_ident.name.to_string(), false)
188             } else if mirrored_exprs(cx, left_expr, right_ident, right_expr, left_ident) {
189                 (Sugg::hir(cx, left_expr, "..").to_string(), right_ident.name.to_string(), true)
190             } else {
191                 return None;
192             };
193             let vec_name = Sugg::hir(cx, &args[0], "..").to_string();
194             let unstable = name == "sort_unstable_by";
195
196             if_chain! {
197             if let ExprKind::Path(QPath::Resolved(_, Path {
198                 segments: [PathSegment { ident: left_name, .. }], ..
199             })) = &left_expr.kind;
200             if left_name == left_ident;
201             if cx.tcx.get_diagnostic_item(sym::Ord).map_or(false, |id| {
202                 implements_trait(cx, cx.typeck_results().expr_ty(left_expr), id, &[])
203             });
204                 then {
205                     return Some(LintTrigger::Sort(SortDetection { vec_name, unstable }));
206                 }
207             }
208
209             if !expr_borrows(cx, left_expr) {
210                 return Some(LintTrigger::SortByKey(SortByKeyDetection {
211                     vec_name,
212                     closure_arg,
213                     closure_body,
214                     reverse,
215                     unstable,
216                 }));
217             }
218         }
219     }
220
221     None
222 }
223
224 fn expr_borrows(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
225     let ty = cx.typeck_results().expr_ty(expr);
226     matches!(ty.kind(), ty::Ref(..))
227         || ty
228             .walk(cx.tcx)
229             .any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)))
230 }
231
232 impl LateLintPass<'_> for UnnecessarySortBy {
233     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
234         match detect_lint(cx, expr) {
235             Some(LintTrigger::SortByKey(trigger)) => span_lint_and_sugg(
236                 cx,
237                 UNNECESSARY_SORT_BY,
238                 expr.span,
239                 "use Vec::sort_by_key here instead",
240                 "try",
241                 format!(
242                     "{}.sort{}_by_key(|{}| {})",
243                     trigger.vec_name,
244                     if trigger.unstable { "_unstable" } else { "" },
245                     trigger.closure_arg,
246                     if trigger.reverse {
247                         format!("Reverse({})", trigger.closure_body)
248                     } else {
249                         trigger.closure_body.to_string()
250                     },
251                 ),
252                 if trigger.reverse {
253                     Applicability::MaybeIncorrect
254                 } else {
255                     Applicability::MachineApplicable
256                 },
257             ),
258             Some(LintTrigger::Sort(trigger)) => span_lint_and_sugg(
259                 cx,
260                 UNNECESSARY_SORT_BY,
261                 expr.span,
262                 "use Vec::sort here instead",
263                 "try",
264                 format!(
265                     "{}.sort{}()",
266                     trigger.vec_name,
267                     if trigger.unstable { "_unstable" } else { "" },
268                 ),
269                 Applicability::MachineApplicable,
270             ),
271             None => {},
272         }
273     }
274 }