1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::ty::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};
11 use rustc_span::symbol::Ident;
14 declare_clippy_lint! {
16 /// Detects uses of `Vec::sort_by` passing in a closure
17 /// which compares the two arguments, either directly or indirectly.
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
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.
32 /// # impl A { fn foo(&self) {} }
33 /// # let mut vec: Vec<A> = Vec::new();
34 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
39 /// # impl A { fn foo(&self) {} }
40 /// # let mut vec: Vec<A> = Vec::new();
41 /// vec.sort_by_key(|a| a.foo());
43 pub UNNECESSARY_SORT_BY,
45 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
48 declare_lint_pass!(UnnecessarySortBy => [UNNECESSARY_SORT_BY]);
52 SortByKey(SortByKeyDetection),
55 struct SortDetection {
60 struct SortByKeyDetection {
68 /// Detect if the two expressions are mirrored (identical, except one
69 /// contains a and the other replaces it with b)
77 match (&a_expr.kind, &b_expr.kind) {
78 // Two boxes with mirrored contents
79 (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => {
80 mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
82 // Two arrays with mirrored contents
83 (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => {
84 iter::zip(*left_exprs, *right_exprs)
85 .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
87 // The two exprs are function calls.
88 // Check to see that the function itself and its arguments are mirrored
89 (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
90 mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
91 && iter::zip(*left_args, *right_args)
92 .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
94 // The two exprs are method calls.
95 // Check to see that the function is the same and the arguments are mirrored
96 // This is enough because the receiver of the method is listed in the arguments
98 ExprKind::MethodCall(left_segment, _, left_args, _),
99 ExprKind::MethodCall(right_segment, _, right_args, _),
101 left_segment.ident == right_segment.ident
102 && iter::zip(*left_args, *right_args)
103 .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
105 // Two tuples with mirrored contents
106 (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => {
107 iter::zip(*left_exprs, *right_exprs)
108 .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
110 // Two binary ops, which are the same operation and which have mirrored arguments
111 (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
112 left_op.node == right_op.node
113 && mirrored_exprs(cx, left_left, a_ident, right_left, b_ident)
114 && mirrored_exprs(cx, left_right, a_ident, right_right, b_ident)
116 // Two unary ops, which are the same operation and which have the same argument
117 (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
118 left_op == right_op && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
120 // The two exprs are literals of some kind
121 (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
122 (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(cx, left, a_ident, right, b_ident),
123 (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
124 mirrored_exprs(cx, left_block, a_ident, right_block, b_ident)
126 (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
127 left_ident.name == right_ident.name && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident)
129 // Two paths: either one is a and the other is b, or they're identical to each other
131 ExprKind::Path(QPath::Resolved(
134 segments: left_segments,
138 ExprKind::Path(QPath::Resolved(
141 segments: right_segments,
146 (iter::zip(*left_segments, *right_segments)
147 .all(|(left, right)| left.ident == right.ident)
150 .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
151 || (left_segments.len() == 1
152 && &left_segments[0].ident == a_ident
153 && right_segments.len() == 1
154 && &right_segments[0].ident == b_ident)
156 // Matching expressions, but one or both is borrowed
158 ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
159 ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
160 ) => left_kind == right_kind && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident),
161 (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => {
162 mirrored_exprs(cx, a_expr, a_ident, right_expr, b_ident)
164 (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident),
169 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintTrigger> {
171 if let ExprKind::MethodCall(name_ident, _, args, _) = &expr.kind;
172 if let name = name_ident.ident.name.to_ident_string();
173 if name == "sort_by" || name == "sort_unstable_by";
174 if let [vec, Expr { kind: ExprKind::Closure(_, _, closure_body_id, _, _), .. }] = args;
175 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(vec), sym::vec_type);
176 if let closure_body = cx.tcx.hir().body(*closure_body_id);
178 Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
179 Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
180 ] = &closure_body.params;
181 if let ExprKind::MethodCall(method_path, _, [ref left_expr, ref right_expr], _) = &closure_body.value.kind;
182 if method_path.ident.name == sym::cmp;
184 let (closure_body, closure_arg, reverse) = if mirrored_exprs(
191 (Sugg::hir(cx, &left_expr, "..").to_string(), left_ident.name.to_string(), false)
192 } else if mirrored_exprs(&cx, &left_expr, &right_ident, &right_expr, &left_ident) {
193 (Sugg::hir(cx, &left_expr, "..").to_string(), right_ident.name.to_string(), true)
197 let vec_name = Sugg::hir(cx, &args[0], "..").to_string();
198 let unstable = name == "sort_unstable_by";
200 if let ExprKind::Path(QPath::Resolved(_, Path {
201 segments: [PathSegment { ident: left_name, .. }], ..
202 })) = &left_expr.kind {
203 if left_name == left_ident {
204 return Some(LintTrigger::Sort(SortDetection { vec_name, unstable }));
208 if !expr_borrows(cx, left_expr) {
209 return Some(LintTrigger::SortByKey(SortByKeyDetection {
223 fn expr_borrows(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
224 let ty = cx.typeck_results().expr_ty(expr);
225 matches!(ty.kind(), ty::Ref(..)) || ty.walk().any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)))
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)) => span_lint_and_sugg(
235 "use Vec::sort_by_key here instead",
238 "{}.sort{}_by_key(|{}| {})",
240 if trigger.unstable { "_unstable" } else { "" },
243 format!("Reverse({})", trigger.closure_body)
245 trigger.closure_body.to_string()
249 Applicability::MaybeIncorrect
251 Applicability::MachineApplicable
254 Some(LintTrigger::Sort(trigger)) => span_lint_and_sugg(
258 "use Vec::sort here instead",
263 if trigger.unstable { "_unstable" } else { "" },
265 Applicability::MachineApplicable,