]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs
Auto merge of #73490 - CAD97:range-unchecked-stepping, r=Amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / unnecessary_sort_by.rs
1 use crate::utils;
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
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_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::Ident;
10
11 declare_clippy_lint! {
12     /// **What it does:**
13     /// Detects when people use `Vec::sort_by` and pass in a function
14     /// which compares the two arguments, either directly or indirectly.
15     ///
16     /// **Why is this bad?**
17     /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
18     /// possible) than to use `Vec::sort_by` and and a more complicated
19     /// closure.
20     ///
21     /// **Known problems:**
22     /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't
23     /// imported by a use statement in the current frame, then a `use`
24     /// statement that imports it will need to be added (which this lint
25     /// can't do).
26     ///
27     /// **Example:**
28     ///
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)) => left_exprs
83             .iter()
84             .zip(right_exprs.iter())
85             .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)),
86         // The two exprs are function calls.
87         // Check to see that the function itself and its arguments are mirrored
88         (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
89             mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
90                 && left_args
91                     .iter()
92                     .zip(right_args.iter())
93                     .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
94         },
95         // The two exprs are method calls.
96         // Check to see that the function is the same and the arguments are mirrored
97         // This is enough because the receiver of the method is listed in the arguments
98         (
99             ExprKind::MethodCall(left_segment, _, left_args, _),
100             ExprKind::MethodCall(right_segment, _, right_args, _),
101         ) => {
102             left_segment.ident == right_segment.ident
103                 && left_args
104                     .iter()
105                     .zip(right_args.iter())
106                     .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
107         },
108         // Two tuples with mirrored contents
109         (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => left_exprs
110             .iter()
111             .zip(right_exprs.iter())
112             .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)),
113         // Two binary ops, which are the same operation and which have mirrored arguments
114         (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
115             left_op.node == right_op.node
116                 && mirrored_exprs(cx, left_left, a_ident, right_left, b_ident)
117                 && mirrored_exprs(cx, left_right, a_ident, right_right, b_ident)
118         },
119         // Two unary ops, which are the same operation and which have the same argument
120         (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
121             left_op == right_op && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
122         },
123         // The two exprs are literals of some kind
124         (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
125         (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(cx, left, a_ident, right, b_ident),
126         (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
127             mirrored_exprs(cx, left_block, a_ident, right_block, b_ident)
128         },
129         (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
130             left_ident.name == right_ident.name && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident)
131         },
132         // Two paths: either one is a and the other is b, or they're identical to each other
133         (
134             ExprKind::Path(QPath::Resolved(
135                 _,
136                 Path {
137                     segments: left_segments,
138                     ..
139                 },
140             )),
141             ExprKind::Path(QPath::Resolved(
142                 _,
143                 Path {
144                     segments: right_segments,
145                     ..
146                 },
147             )),
148         ) => {
149             (left_segments
150                 .iter()
151                 .zip(right_segments.iter())
152                 .all(|(left, right)| left.ident == right.ident)
153                 && left_segments
154                     .iter()
155                     .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
156                 || (left_segments.len() == 1
157                     && &left_segments[0].ident == a_ident
158                     && right_segments.len() == 1
159                     && &right_segments[0].ident == b_ident)
160         },
161         // Matching expressions, but one or both is borrowed
162         (
163             ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
164             ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
165         ) => left_kind == right_kind && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident),
166         (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => {
167             mirrored_exprs(cx, a_expr, a_ident, right_expr, b_ident)
168         },
169         (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident),
170         _ => false,
171     }
172 }
173
174 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintTrigger> {
175     if_chain! {
176         if let ExprKind::MethodCall(name_ident, _, args, _) = &expr.kind;
177         if let name = name_ident.ident.name.to_ident_string();
178         if name == "sort_by" || name == "sort_unstable_by";
179         if let [vec, Expr { kind: ExprKind::Closure(_, _, closure_body_id, _, _), .. }] = args;
180         if utils::match_type(cx, &cx.tables().expr_ty(vec), &paths::VEC);
181         if let closure_body = cx.tcx.hir().body(*closure_body_id);
182         if let &[
183             Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
184             Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
185         ] = &closure_body.params;
186         if let ExprKind::MethodCall(method_path, _, [ref left_expr, ref right_expr], _) = &closure_body.value.kind;
187         if method_path.ident.name.to_ident_string() == "cmp";
188         then {
189             let (closure_body, closure_arg, reverse) = if mirrored_exprs(
190                 &cx,
191                 &left_expr,
192                 &left_ident,
193                 &right_expr,
194                 &right_ident
195             ) {
196                 (Sugg::hir(cx, &left_expr, "..").to_string(), left_ident.name.to_string(), false)
197             } else if mirrored_exprs(&cx, &left_expr, &right_ident, &right_expr, &left_ident) {
198                 (Sugg::hir(cx, &left_expr, "..").to_string(), right_ident.name.to_string(), true)
199             } else {
200                 return None;
201             };
202             let vec_name = Sugg::hir(cx, &args[0], "..").to_string();
203             let unstable = name == "sort_unstable_by";
204             if_chain! {
205                 if let ExprKind::Path(QPath::Resolved(_, Path {
206                     segments: [PathSegment { ident: left_name, .. }], ..
207                 })) = &left_expr.kind;
208                 if left_name == left_ident;
209                 then {
210                     Some(LintTrigger::Sort(SortDetection { vec_name, unstable }))
211                 }
212                 else {
213                     Some(LintTrigger::SortByKey(SortByKeyDetection {
214                         vec_name,
215                         unstable,
216                         closure_arg,
217                         closure_body,
218                         reverse
219                     }))
220                 }
221             }
222         } else {
223             None
224         }
225     }
226 }
227
228 impl LateLintPass<'_> for UnnecessarySortBy {
229     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
230         match detect_lint(cx, expr) {
231             Some(LintTrigger::SortByKey(trigger)) => utils::span_lint_and_sugg(
232                 cx,
233                 UNNECESSARY_SORT_BY,
234                 expr.span,
235                 "use Vec::sort_by_key here instead",
236                 "try",
237                 format!(
238                     "{}.sort{}_by_key(|&{}| {})",
239                     trigger.vec_name,
240                     if trigger.unstable { "_unstable" } else { "" },
241                     trigger.closure_arg,
242                     if trigger.reverse {
243                         format!("Reverse({})", trigger.closure_body)
244                     } else {
245                         trigger.closure_body.to_string()
246                     },
247                 ),
248                 if trigger.reverse {
249                     Applicability::MaybeIncorrect
250                 } else {
251                     Applicability::MachineApplicable
252                 },
253             ),
254             Some(LintTrigger::Sort(trigger)) => utils::span_lint_and_sugg(
255                 cx,
256                 UNNECESSARY_SORT_BY,
257                 expr.span,
258                 "use Vec::sort here instead",
259                 "try",
260                 format!(
261                     "{}.sort{}()",
262                     trigger.vec_name,
263                     if trigger.unstable { "_unstable" } else { "" },
264                 ),
265                 Applicability::MachineApplicable,
266             ),
267             None => {},
268         }
269     }
270 }