1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_trait_method;
3 use clippy_utils::sugg::Sugg;
4 use clippy_utils::ty::implements_trait;
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Closure, Expr, ExprKind, Mutability, Param, Pat, PatKind, Path, PathSegment, QPath};
8 use rustc_lint::LateContext;
9 use rustc_middle::ty::{self, subst::GenericArgKind};
11 use rustc_span::symbol::Ident;
14 use super::UNNECESSARY_SORT_BY;
18 SortByKey(SortByKeyDetection),
21 struct SortDetection {
25 struct SortByKeyDetection {
32 /// Detect if the two expressions are mirrored (identical, except one
33 /// contains a and the other replaces it with b)
34 fn mirrored_exprs(a_expr: &Expr<'_>, a_ident: &Ident, b_expr: &Expr<'_>, b_ident: &Ident) -> bool {
35 match (&a_expr.kind, &b_expr.kind) {
36 // Two boxes with mirrored contents
37 (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => {
38 mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
40 // Two arrays with mirrored contents
41 (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => {
42 iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
44 // The two exprs are function calls.
45 // Check to see that the function itself and its arguments are mirrored
46 (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
47 mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
48 && iter::zip(*left_args, *right_args).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
50 // The two exprs are method calls.
51 // Check to see that the function is the same and the arguments are mirrored
52 // This is enough because the receiver of the method is listed in the arguments
53 (ExprKind::MethodCall(left_segment, left_args, _), ExprKind::MethodCall(right_segment, right_args, _)) => {
54 left_segment.ident == right_segment.ident
55 && iter::zip(*left_args, *right_args).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
57 // Two tuples with mirrored contents
58 (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => {
59 iter::zip(*left_exprs, *right_exprs).all(|(left, right)| mirrored_exprs(left, a_ident, right, b_ident))
61 // Two binary ops, which are the same operation and which have mirrored arguments
62 (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
63 left_op.node == right_op.node
64 && mirrored_exprs(left_left, a_ident, right_left, b_ident)
65 && mirrored_exprs(left_right, a_ident, right_right, b_ident)
67 // Two unary ops, which are the same operation and which have the same argument
68 (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
69 left_op == right_op && mirrored_exprs(left_expr, a_ident, right_expr, b_ident)
71 // The two exprs are literals of some kind
72 (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
73 (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(left, a_ident, right, b_ident),
74 (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
75 mirrored_exprs(left_block, a_ident, right_block, b_ident)
77 (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
78 left_ident.name == right_ident.name && mirrored_exprs(left_expr, a_ident, right_expr, right_ident)
80 // Two paths: either one is a and the other is b, or they're identical to each other
82 ExprKind::Path(QPath::Resolved(
85 segments: left_segments,
89 ExprKind::Path(QPath::Resolved(
92 segments: right_segments,
97 (iter::zip(*left_segments, *right_segments).all(|(left, right)| left.ident == right.ident)
100 .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
101 || (left_segments.len() == 1
102 && &left_segments[0].ident == a_ident
103 && right_segments.len() == 1
104 && &right_segments[0].ident == b_ident)
106 // Matching expressions, but one or both is borrowed
108 ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
109 ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
110 ) => left_kind == right_kind && mirrored_exprs(left_expr, a_ident, right_expr, b_ident),
111 (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => mirrored_exprs(a_expr, a_ident, right_expr, b_ident),
112 (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(left_expr, a_ident, b_expr, b_ident),
117 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<'_>) -> Option<LintTrigger> {
119 if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
120 if let Some(impl_id) = cx.tcx.impl_of_method(method_id);
121 if cx.tcx.type_of(impl_id).is_slice();
122 if let ExprKind::Closure(&Closure { body, .. }) = arg.kind;
123 if let closure_body = cx.tcx.hir().body(body);
125 Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
126 Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
127 ] = &closure_body.params;
128 if let ExprKind::MethodCall(method_path, [left_expr, right_expr], _) = closure_body.value.kind;
129 if method_path.ident.name == sym::cmp;
130 if is_trait_method(cx, &closure_body.value, sym::Ord);
132 let (closure_body, closure_arg, reverse) = if mirrored_exprs(
138 (Sugg::hir(cx, left_expr, "..").to_string(), left_ident.name.to_string(), false)
139 } else if mirrored_exprs(left_expr, right_ident, right_expr, left_ident) {
140 (Sugg::hir(cx, left_expr, "..").to_string(), right_ident.name.to_string(), true)
144 let vec_name = Sugg::hir(cx, recv, "..").to_string();
147 if let ExprKind::Path(QPath::Resolved(_, Path {
148 segments: [PathSegment { ident: left_name, .. }], ..
149 })) = &left_expr.kind;
150 if left_name == left_ident;
151 if cx.tcx.get_diagnostic_item(sym::Ord).map_or(false, |id| {
152 implements_trait(cx, cx.typeck_results().expr_ty(left_expr), id, &[])
155 return Some(LintTrigger::Sort(SortDetection { vec_name }));
159 if !expr_borrows(cx, left_expr) {
160 return Some(LintTrigger::SortByKey(SortByKeyDetection {
173 fn expr_borrows(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
174 let ty = cx.typeck_results().expr_ty(expr);
175 matches!(ty.kind(), ty::Ref(..)) || ty.walk().any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)))
178 pub(super) fn check<'tcx>(
179 cx: &LateContext<'tcx>,
180 expr: &'tcx Expr<'_>,
181 recv: &'tcx Expr<'_>,
185 match detect_lint(cx, expr, recv, arg) {
186 Some(LintTrigger::SortByKey(trigger)) => span_lint_and_sugg(
190 "use Vec::sort_by_key here instead",
193 "{}.sort{}_by_key(|{}| {})",
195 if is_unstable { "_unstable" } else { "" },
198 format!("std::cmp::Reverse({})", trigger.closure_body)
200 trigger.closure_body.to_string()
204 Applicability::MaybeIncorrect
206 Applicability::MachineApplicable
209 Some(LintTrigger::Sort(trigger)) => span_lint_and_sugg(
213 "use Vec::sort here instead",
218 if is_unstable { "_unstable" } else { "" },
220 Applicability::MachineApplicable,