]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/unnecessary_sort_by.rs
Auto merge of #9258 - Serial-ATA:unused-peekable, r=Alexendoo
[rust.git] / clippy_lints / src / methods / unnecessary_sort_by.rs
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};
10 use rustc_span::sym;
11 use rustc_span::symbol::Ident;
12 use std::iter;
13
14 use super::UNNECESSARY_SORT_BY;
15
16 enum LintTrigger {
17     Sort(SortDetection),
18     SortByKey(SortByKeyDetection),
19 }
20
21 struct SortDetection {
22     vec_name: String,
23 }
24
25 struct SortByKeyDetection {
26     vec_name: String,
27     closure_arg: String,
28     closure_body: String,
29     reverse: bool,
30 }
31
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)
39         },
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))
43         },
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))
49         },
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))
56         },
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))
60         },
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)
66         },
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)
70         },
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)
76         },
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)
79         },
80         // Two paths: either one is a and the other is b, or they're identical to each other
81         (
82             ExprKind::Path(QPath::Resolved(
83                 _,
84                 Path {
85                     segments: left_segments,
86                     ..
87                 },
88             )),
89             ExprKind::Path(QPath::Resolved(
90                 _,
91                 Path {
92                     segments: right_segments,
93                     ..
94                 },
95             )),
96         ) => {
97             (iter::zip(*left_segments, *right_segments).all(|(left, right)| left.ident == right.ident)
98                 && left_segments
99                     .iter()
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)
105         },
106         // Matching expressions, but one or both is borrowed
107         (
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),
113         _ => false,
114     }
115 }
116
117 fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<'_>) -> Option<LintTrigger> {
118     if_chain! {
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);
124         if let &[
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);
131         then {
132             let (closure_body, closure_arg, reverse) = if mirrored_exprs(
133                 left_expr,
134                 left_ident,
135                 right_expr,
136                 right_ident
137             ) {
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)
141             } else {
142                 return None;
143             };
144             let vec_name = Sugg::hir(cx, recv, "..").to_string();
145
146             if_chain! {
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, &[])
153                 });
154                 then {
155                     return Some(LintTrigger::Sort(SortDetection { vec_name }));
156                 }
157             }
158
159             if !expr_borrows(cx, left_expr) {
160                 return Some(LintTrigger::SortByKey(SortByKeyDetection {
161                     vec_name,
162                     closure_arg,
163                     closure_body,
164                     reverse,
165                 }));
166             }
167         }
168     }
169
170     None
171 }
172
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(_)))
176 }
177
178 pub(super) fn check<'tcx>(
179     cx: &LateContext<'tcx>,
180     expr: &'tcx Expr<'_>,
181     recv: &'tcx Expr<'_>,
182     arg: &'tcx Expr<'_>,
183     is_unstable: bool,
184 ) {
185     match detect_lint(cx, expr, recv, arg) {
186         Some(LintTrigger::SortByKey(trigger)) => span_lint_and_sugg(
187             cx,
188             UNNECESSARY_SORT_BY,
189             expr.span,
190             "use Vec::sort_by_key here instead",
191             "try",
192             format!(
193                 "{}.sort{}_by_key(|{}| {})",
194                 trigger.vec_name,
195                 if is_unstable { "_unstable" } else { "" },
196                 trigger.closure_arg,
197                 if trigger.reverse {
198                     format!("std::cmp::Reverse({})", trigger.closure_body)
199                 } else {
200                     trigger.closure_body.to_string()
201                 },
202             ),
203             if trigger.reverse {
204                 Applicability::MaybeIncorrect
205             } else {
206                 Applicability::MachineApplicable
207             },
208         ),
209         Some(LintTrigger::Sort(trigger)) => span_lint_and_sugg(
210             cx,
211             UNNECESSARY_SORT_BY,
212             expr.span,
213             "use Vec::sort here instead",
214             "try",
215             format!(
216                 "{}.sort{}()",
217                 trigger.vec_name,
218                 if is_unstable { "_unstable" } else { "" },
219             ),
220             Applicability::MachineApplicable,
221         ),
222         None => {},
223     }
224 }