]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/stable_sort_primitive.rs
Auto merge of #87445 - amalik18:issue-83584-fix, r=kennytm
[rust.git] / src / tools / clippy / clippy_lints / src / stable_sort_primitive.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::{is_slice_of_primitives, sugg::Sugg};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8
9 declare_clippy_lint! {
10     /// ### What it does
11     /// When sorting primitive values (integers, bools, chars, as well
12     /// as arrays, slices, and tuples of such items), it is better to
13     /// use an unstable sort than a stable sort.
14     ///
15     /// ### Why is this bad?
16     /// Using a stable sort consumes more memory and cpu cycles. Because
17     /// values which compare equal are identical, preserving their
18     /// relative order (the guarantee that a stable sort provides) means
19     /// nothing, while the extra costs still apply.
20     ///
21     /// ### Example
22     /// ```rust
23     /// let mut vec = vec![2, 1, 3];
24     /// vec.sort();
25     /// ```
26     /// Use instead:
27     /// ```rust
28     /// let mut vec = vec![2, 1, 3];
29     /// vec.sort_unstable();
30     /// ```
31     pub STABLE_SORT_PRIMITIVE,
32     perf,
33     "use of sort() when sort_unstable() is equivalent"
34 }
35
36 declare_lint_pass!(StableSortPrimitive => [STABLE_SORT_PRIMITIVE]);
37
38 /// The three "kinds" of sorts
39 enum SortingKind {
40     Vanilla,
41     /* The other kinds of lint are currently commented out because they
42      * can map distinct values to equal ones. If the key function is
43      * provably one-to-one, or if the Cmp function conserves equality,
44      * then they could be linted on, but I don't know if we can check
45      * for that. */
46
47     /* ByKey,
48      * ByCmp, */
49 }
50 impl SortingKind {
51     /// The name of the stable version of this kind of sort
52     fn stable_name(&self) -> &str {
53         match self {
54             SortingKind::Vanilla => "sort",
55             /* SortingKind::ByKey => "sort_by_key",
56              * SortingKind::ByCmp => "sort_by", */
57         }
58     }
59     /// The name of the unstable version of this kind of sort
60     fn unstable_name(&self) -> &str {
61         match self {
62             SortingKind::Vanilla => "sort_unstable",
63             /* SortingKind::ByKey => "sort_unstable_by_key",
64              * SortingKind::ByCmp => "sort_unstable_by", */
65         }
66     }
67     /// Takes the name of a function call and returns the kind of sort
68     /// that corresponds to that function name (or None if it isn't)
69     fn from_stable_name(name: &str) -> Option<SortingKind> {
70         match name {
71             "sort" => Some(SortingKind::Vanilla),
72             // "sort_by" => Some(SortingKind::ByCmp),
73             // "sort_by_key" => Some(SortingKind::ByKey),
74             _ => None,
75         }
76     }
77 }
78
79 /// A detected instance of this lint
80 struct LintDetection {
81     slice_name: String,
82     method: SortingKind,
83     method_args: String,
84     slice_type: String,
85 }
86
87 fn detect_stable_sort_primitive(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintDetection> {
88     if_chain! {
89         if let ExprKind::MethodCall(method_name, _, args, _) = &expr.kind;
90         if let Some(slice) = &args.get(0);
91         if let Some(method) = SortingKind::from_stable_name(&method_name.ident.name.as_str());
92         if let Some(slice_type) = is_slice_of_primitives(cx, slice);
93         then {
94             let args_str = args.iter().skip(1).map(|arg| Sugg::hir(cx, arg, "..").to_string()).collect::<Vec<String>>().join(", ");
95             Some(LintDetection { slice_name: Sugg::hir(cx, slice, "..").to_string(), method, method_args: args_str, slice_type })
96         } else {
97             None
98         }
99     }
100 }
101
102 impl LateLintPass<'_> for StableSortPrimitive {
103     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
104         if let Some(detection) = detect_stable_sort_primitive(cx, expr) {
105             span_lint_and_then(
106                 cx,
107                 STABLE_SORT_PRIMITIVE,
108                 expr.span,
109                 format!(
110                     "used `{}` on primitive type `{}`",
111                     detection.method.stable_name(),
112                     detection.slice_type,
113                 )
114                 .as_str(),
115                 |diag| {
116                     diag.span_suggestion(
117                         expr.span,
118                         "try",
119                         format!(
120                             "{}.{}({})",
121                             detection.slice_name,
122                             detection.method.unstable_name(),
123                             detection.method_args,
124                         ),
125                         Applicability::MachineApplicable,
126                     );
127                     diag.note(
128                         "an unstable sort would perform faster without any observable difference for this data type",
129                     );
130                 },
131             );
132         }
133     }
134 }