]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unnecessary_sort_by.rs
Auto merge of #9148 - arieluy:then_some_unwrap_or, r=Jarcho
[rust.git] / 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::{Closure, 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     #[clippy::version = "1.46.0"]
43     pub UNNECESSARY_SORT_BY,
44     complexity,
45     "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
46 }
47
48 declare_lint_pass!(UnnecessarySortBy => [UNNECESSARY_SORT_BY]);
49
50 enum LintTrigger {
51     Sort(SortDetection),
52     SortByKey(SortByKeyDetection),
53 }
54
55 struct SortDetection {
56     vec_name: String,
57     unstable: bool,
58 }
59
60 struct SortByKeyDetection {
61     vec_name: String,
62     closure_arg: String,
63     closure_body: String,
64     reverse: bool,
65     unstable: bool,
66 }
67
68 /// Detect if the two expressions are mirrored (identical, except one
69 /// contains a and the other replaces it with b)
70 fn mirrored_exprs(a_expr: &Expr<'_>, a_ident: &Ident, b_expr: &Expr<'_>, b_ident: &Ident) -> bool {
71     match (&a_expr.kind, &b_expr.kind) {
72         // Two boxes with mirrored contents
73         (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => {
74             mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
75         },
76         // Two arrays with mirrored contents
77         (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => {
78             iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
79         },
80         // The two exprs are function calls.
81         // Check to see that the function itself and its arguments are mirrored
82         (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
83             mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
84                 && iter::zip(*left_args, *right_args).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
85         },
86         // The two exprs are method calls.
87         // Check to see that the function is the same and the arguments are mirrored
88         // This is enough because the receiver of the method is listed in the arguments
89         (ExprKind::MethodCall(left_segment, left_args, _), ExprKind::MethodCall(right_segment, right_args, _)) => {
90             left_segment.ident == right_segment.ident
91                 && iter::zip(*left_args, *right_args).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
92         },
93         // Two tuples with mirrored contents
94         (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => {
95             iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
96         },
97         // Two binary ops, which are the same operation and which have mirrored arguments
98         (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
99             left_op.node == right_op.node
100                 && mirrored_exprs(left_left, a_ident, right_left, b_ident)
101                 && mirrored_exprs(left_right, a_ident, right_right, b_ident)
102         },
103         // Two unary ops, which are the same operation and which have the same argument
104         (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
105             left_op == right_op && mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
106         },
107         // The two exprs are literals of some kind
108         (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
109         (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(left, a_ident, right, b_ident),
110         (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
111             mirrored_exprs(left_block, a_ident, right_block, b_ident)
112         },
113         (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
114             left_ident.name == right_ident.name && mirrored_exprs(left_expr, a_ident, right_expr, right_ident)
115         },
116         // Two paths: either one is a and the other is b, or they're identical to each other
117         (
118             ExprKind::Path(QPath::Resolved(
119                 _,
120                 Path {
121                     segments: left_segments,
122                     ..
123                 },
124             )),
125             ExprKind::Path(QPath::Resolved(
126                 _,
127                 Path {
128                     segments: right_segments,
129                     ..
130                 },
131             )),
132         ) => {
133             (iter::zip(*left_segments, *right_segments).all(|(left, right)| left.ident == right.ident)
134                 && left_segments
135                     .iter()
136                     .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
137                 || (left_segments.len() == 1
138                     && &left_segments[0].ident == a_ident
139                     && right_segments.len() == 1
140                     && &right_segments[0].ident == b_ident)
141         },
142         // Matching expressions, but one or both is borrowed
143         (
144             ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
145             ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
146         ) => left_kind == right_kind && mirrored_exprs(left_expr, a_ident, right_expr, b_ident),
147         (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => mirrored_exprs(a_expr, a_ident, right_expr, b_ident),
148         (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(left_expr, a_ident, b_expr, b_ident),
149         _ => false,
150     }
151 }
152
153 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintTrigger> {
154     if_chain! {
155         if let ExprKind::MethodCall(name_ident, args, _) = &expr.kind;
156         if let name = name_ident.ident.name.to_ident_string();
157         if name == "sort_by" || name == "sort_unstable_by";
158         if let [vec, Expr { kind: ExprKind::Closure(Closure { body: closure_body_id, .. }), .. }] = args;
159         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(vec), sym::Vec);
160         if let closure_body = cx.tcx.hir().body(*closure_body_id);
161         if let &[
162             Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
163             Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
164         ] = &closure_body.params;
165         if let ExprKind::MethodCall(method_path, [ref left_expr, ref right_expr], _) = &closure_body.value.kind;
166         if method_path.ident.name == sym::cmp;
167         then {
168             let (closure_body, closure_arg, reverse) = if mirrored_exprs(
169                 left_expr,
170                 left_ident,
171                 right_expr,
172                 right_ident
173             ) {
174                 (Sugg::hir(cx, left_expr, "..").to_string(), left_ident.name.to_string(), false)
175             } else if mirrored_exprs(left_expr, right_ident, right_expr, left_ident) {
176                 (Sugg::hir(cx, left_expr, "..").to_string(), right_ident.name.to_string(), true)
177             } else {
178                 return None;
179             };
180             let vec_name = Sugg::hir(cx, &args[0], "..").to_string();
181             let unstable = name == "sort_unstable_by";
182
183             if_chain! {
184             if let ExprKind::Path(QPath::Resolved(_, Path {
185                 segments: [PathSegment { ident: left_name, .. }], ..
186             })) = &left_expr.kind;
187             if left_name == left_ident;
188             if cx.tcx.get_diagnostic_item(sym::Ord).map_or(false, |id| {
189                 implements_trait(cx, cx.typeck_results().expr_ty(left_expr), id, &[])
190             });
191                 then {
192                     return Some(LintTrigger::Sort(SortDetection { vec_name, unstable }));
193                 }
194             }
195
196             if !expr_borrows(cx, left_expr) {
197                 return Some(LintTrigger::SortByKey(SortByKeyDetection {
198                     vec_name,
199                     closure_arg,
200                     closure_body,
201                     reverse,
202                     unstable,
203                 }));
204             }
205         }
206     }
207
208     None
209 }
210
211 fn expr_borrows(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
212     let ty = cx.typeck_results().expr_ty(expr);
213     matches!(ty.kind(), ty::Ref(..)) || ty.walk().any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)))
214 }
215
216 impl LateLintPass<'_> for UnnecessarySortBy {
217     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
218         match detect_lint(cx, expr) {
219             Some(LintTrigger::SortByKey(trigger)) => span_lint_and_sugg(
220                 cx,
221                 UNNECESSARY_SORT_BY,
222                 expr.span,
223                 "use Vec::sort_by_key here instead",
224                 "try",
225                 format!(
226                     "{}.sort{}_by_key(|{}| {})",
227                     trigger.vec_name,
228                     if trigger.unstable { "_unstable" } else { "" },
229                     trigger.closure_arg,
230                     if trigger.reverse {
231                         format!("std::cmp::Reverse({})", trigger.closure_body)
232                     } else {
233                         trigger.closure_body.to_string()
234                     },
235                 ),
236                 if trigger.reverse {
237                     Applicability::MaybeIncorrect
238                 } else {
239                     Applicability::MachineApplicable
240                 },
241             ),
242             Some(LintTrigger::Sort(trigger)) => span_lint_and_sugg(
243                 cx,
244                 UNNECESSARY_SORT_BY,
245                 expr.span,
246                 "use Vec::sort here instead",
247                 "try",
248                 format!(
249                     "{}.sort{}()",
250                     trigger.vec_name,
251                     if trigger.unstable { "_unstable" } else { "" },
252                 ),
253                 Applicability::MachineApplicable,
254             ),
255             None => {},
256         }
257     }
258 }