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::share_a_case_shape(left, right))
66    }
67
68    // Two segments compare the same way under both comparators only when they
69    // are of the same shape, and an initial capital is not enough to say so.
70    // `WAL_V2_MAGIC` and `WalRecord` both open with one and the editions still
71    // disagree: measured, 2021 puts `WalRecord` first and 2024 `WAL_V2_MAGIC`,
72    // the same split already recorded for `Value` against `from_str`. Reading
73    // only the first character called that pair same-case and demanded the
74    // alphabet, which is a file `cargo fmt` rewrites on every run -- found in
75    // `etheram-ibft`, where it cost sixteen offences no edit could clear and
76    // both import rules had to be stood down to keep stage 1 green.
77    //
78    // Shape is the initial and whether the segment is all capitals, because
79    // those are the two axes the disagreement runs along. Segments sharing both
80    // -- `ALPHA_TWO` against `ZETA_ONE`, `Alpha` against `Zeta`, `alpha`
81    // against `zeta` -- were measured to sort identically under 2021, 2024 and
82    // a plain sort, so those are still judged.
83    fn share_a_case_shape(left: &str, right: &str) -> bool {
84        Self::is_uppercase(left) == Self::is_uppercase(right)
85            && Self::is_all_capitals(left) == Self::is_all_capitals(right)
86    }
87
88    // Capitals and no lowercase. Digits and underscores decide nothing, so `V2`
89    // reads as capitals and `v2` does not.
90    fn is_all_capitals(segment: &str) -> bool {
91        segment.chars().any(char::is_uppercase) && !segment.chars().any(char::is_lowercase)
92    }
93
94    // One path continues the other: `alloc::vec` beside `alloc::vec::Vec`.
95    //
96    // `diverges_by_case` cannot see this, because it looks for the first pair of
97    // segments that differ and there is no such pair -- the difference is
98    // between a segment and nothing at all. Compared as written the shorter line
99    // ends in `;` (59) where the longer carries on with `::` (58), so a plain
100    // sort demands the longer path first no matter what follows, while rustfmt
101    // demands the shorter. Every extension is a disagreement, so every extension
102    // stands down.
103    //
104    // A rename is not an extension. `bbb as ccc` is one segment rather than
105    // `bbb` followed by another, so the pair falls through to the alphabet,
106    // which is what rustfmt does with it too.
107    fn one_extends_the_other(previous: &str, item: &str) -> bool {
108        let (left, right) = (Self::segments(previous), Self::segments(item));
109        let shared = left.len().min(right.len());
110        left.len() != right.len() && left[..shared] == right[..shared]
111    }
112
113    // The first segment, not a prefix: a crate genuinely named `crateful` sorts
114    // alphabetically like anything else.
115    fn first_segment(import: &str) -> &str {
116        Self::segments(import).first().copied().unwrap_or_default()
117    }
118
119    fn is_uppercase(segment: &str) -> bool {
120        segment.chars().next().is_some_and(char::is_uppercase)
121    }
122
123    fn segments(import: &str) -> Vec<&str> {
124        import
125            .trim()
126            .trim_start_matches("pub ")
127            .trim_start_matches("use ")
128            .trim_start()
129            .trim_end_matches(';')
130            .trim_start_matches("::")
131            .split("::")
132            .map(str::trim)
133            .collect()
134    }
135}