Skip to main content

stern4rust/finding/model/
import_path.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5// The imports whose order rustfmt decides rather than the alphabet.
6//
7// rustfmt sorts `self`, `super` and `crate` ahead of every other path. It also
8// treats case as significant -- and which direction it leans depends on the
9// style edition, which is the part worth measuring rather than guessing:
10//
11// |                                       | 2021         | 2024         |
12// |---------------------------------------|--------------|--------------|
13// | `Bbb::gamma` against `zzz::last`       | sorts last   | sorts first  |
14// | `serde_json::Value` against `from_str` | `from_str`   | `Value`      |
15//
16// The two editions disagree with each other, so no single alphabet can be
17// right for both, and this crate cannot know which one the crate under
18// inspection compiles with. That is the argument for standing down rather than
19// picking a side: declining to judge is correct under either edition, while
20// demanding an order would be wrong under one of them.
21//
22// None of it matches a plain alphabetic sort, and unlike every other
23// disagreement this tool could have with a formatter, this one has no
24// resolution: `cargo fmt` writes one order, the rule would demand another, and
25// stage 1 runs the formatter first. A file caught between the two cannot be
26// fixed by hand at all -- each run undoes the last.
27//
28// One shape the two editions do agree on is an extended path, and it is handled
29// below for that reason rather than this one.
30//
31// So the structure rule stands down on exactly those pairs. Everything else in
32// the import list is still ordered, because among segments of the same case
33// rustfmt's comparator and the alphabet agree.
34//
35// The case rule is pairwise rather than a property of one import, and that
36// distinction is the whole of it. `use serde_json::Value` and
37// `use serde_json::from_str` share a first segment and part company at the
38// second, where one is uppercase and one is not. Neither path is remarkable on
39// its own; only the pair is.
40pub struct ImportPath;
41
42impl ImportPath {
43    // Whether rustfmt, rather than the alphabet, decides this pair's order.
44    pub fn decides_order(previous: &str, item: &str) -> bool {
45        Self::is_specially_ordered(previous)
46            || Self::is_specially_ordered(item)
47            || Self::diverges_by_case(previous, item)
48            || Self::one_extends_the_other(previous, item)
49    }
50
51    pub fn is_specially_ordered(import: &str) -> bool {
52        let first = Self::first_segment(import);
53        matches!(first, "self" | "super" | "crate")
54            || first.chars().next().is_some_and(char::is_uppercase)
55    }
56
57    // Where two paths first differ, and whether the segments there are of
58    // different case. That is the one place the two comparators can disagree:
59    // before it the paths are identical, and after it nothing is compared.
60    fn diverges_by_case(previous: &str, item: &str) -> bool {
61        Self::segments(previous)
62            .into_iter()
63            .zip(Self::segments(item))
64            .find(|(left, right)| left != right)
65            .is_some_and(|(left, right)| Self::is_uppercase(left) != Self::is_uppercase(right))
66    }
67
68    // One path continues the other: `alloc::vec` beside `alloc::vec::Vec`.
69    //
70    // `diverges_by_case` cannot see this, because it looks for the first pair of
71    // segments that differ and there is no such pair -- the difference is
72    // between a segment and nothing at all. Compared as written the shorter line
73    // ends in `;` (59) where the longer carries on with `::` (58), so a plain
74    // sort demands the longer path first no matter what follows, while rustfmt
75    // demands the shorter. Every extension is a disagreement, so every extension
76    // stands down.
77    //
78    // A rename is not an extension. `bbb as ccc` is one segment rather than
79    // `bbb` followed by another, so the pair falls through to the alphabet,
80    // which is what rustfmt does with it too.
81    fn one_extends_the_other(previous: &str, item: &str) -> bool {
82        let (left, right) = (Self::segments(previous), Self::segments(item));
83        let shared = left.len().min(right.len());
84        left.len() != right.len() && left[..shared] == right[..shared]
85    }
86
87    // The first segment, not a prefix: a crate genuinely named `crateful` sorts
88    // alphabetically like anything else.
89    fn first_segment(import: &str) -> &str {
90        Self::segments(import).first().copied().unwrap_or_default()
91    }
92
93    fn is_uppercase(segment: &str) -> bool {
94        segment.chars().next().is_some_and(char::is_uppercase)
95    }
96
97    fn segments(import: &str) -> Vec<&str> {
98        import
99            .trim()
100            .trim_start_matches("pub ")
101            .trim_start_matches("use ")
102            .trim_start()
103            .trim_end_matches(';')
104            .trim_start_matches("::")
105            .split("::")
106            .map(str::trim)
107            .collect()
108    }
109}