Skip to main content

vvv_engine/protocol/
vocabulary.rs

1//! How the answers are read: the output vocabulary of glyphs and words, how
2//! an intent is named, how a count and a time are said. Every interface
3//! renders these — colour is the renderer's (the CLI's `Palette`, the
4//! picker's `Theme`); this is what is being coloured, and it lives with the
5//! shapes it describes so a client reads them the way the CLI prints them.
6
7use std::collections::BTreeSet;
8use std::fmt;
9use std::path::Path;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use super::{BatchIntent, Confidence, Intent, Reason};
13
14/// One mark of the vocabulary. A verdict or a reason maps onto it; a panel
15/// title or a section header names it with its word.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Mark {
18    /// `●` — a declaration.
19    Declaration,
20    /// `●` — a declaration of the same name that is not the one meant.
21    OtherDeclaration,
22    /// `→` — an import, a rewrite's target.
23    Import,
24    /// `→` — the tail of a qualified path.
25    Path,
26    /// `→` — a glob import opens the declaring module.
27    Glob,
28    /// `→` — a path into a package outside the workspace.
29    External,
30    /// `←` — imported by.
31    ImportedBy,
32    /// `↗` — reached through a re-export.
33    ReExport,
34    /// `◎` — an oracle (a build, a language server) placed what syntax could not.
35    Oracle,
36    /// `✓` — will happen; the site resolves to the declaration.
37    Safe,
38    /// `?` — vvv could not verify the site refers to the declaration.
39    Unverified,
40    /// `✗` — will not happen; the site is another declaration's.
41    Other,
42    /// `∅` — nothing; a bare name nothing imports.
43    Nothing,
44    /// `∅` — no declaration to judge against; matched by name.
45    ByName,
46    /// `!` — something to do by hand.
47    ByHand,
48    /// `±` — a structural edit: a `mod` line, a modifier, a file moved.
49    Structure,
50    /// `±` — a match with its replacement.
51    Rewrite,
52    /// `▪` — a row ticked for the commit (the picker's).
53    Ticked,
54    /// `▫` — a row left out (the picker's).
55    Unticked,
56    /// `↩` — what undo reverses.
57    Undo,
58}
59
60impl Mark {
61    pub fn glyph(self) -> char {
62        match self {
63            Self::Declaration | Self::OtherDeclaration => '●',
64            Self::Import | Self::Path | Self::Glob | Self::External => '→',
65            Self::ImportedBy => '←',
66            Self::ReExport => '↗',
67            Self::Oracle => '◎',
68            Self::Safe => '✓',
69            Self::Unverified => '?',
70            Self::Other => '✗',
71            Self::Nothing | Self::ByName => '∅',
72            Self::ByHand => '!',
73            Self::Structure | Self::Rewrite => '±',
74            Self::Ticked => '▪',
75            Self::Unticked => '▫',
76            Self::Undo => '↩',
77        }
78    }
79
80    /// The mark spelled out, for a title or a tag.
81    pub fn word(self) -> &'static str {
82        match self {
83            Self::Declaration => "declaring module",
84            Self::OtherDeclaration => "other decl",
85            Self::Import => "imported",
86            Self::Path => "path",
87            Self::Glob => "glob",
88            Self::External => "external",
89            Self::ImportedBy => "imported by",
90            Self::ReExport => "re-export",
91            Self::Oracle => "oracle",
92            Self::Safe => "safe",
93            Self::Unverified => "unverified",
94            Self::Other => "another declaration's",
95            Self::Nothing => "unresolved",
96            Self::ByName => "by name",
97            Self::ByHand => "by hand",
98            Self::Structure => "structure",
99            Self::Rewrite => "rewrites",
100            Self::Ticked => "ticked",
101            Self::Unticked => "unticked",
102            Self::Undo => "undo",
103        }
104    }
105
106    /// One line on what a reason's mark means at a site (the picker's detail).
107    pub fn meaning(self) -> &'static str {
108        match self {
109            Self::Declaration => "written in the module that declares it",
110            Self::Import => "an import resolving to the declaration brings the name in",
111            Self::Path => "the tail of a path resolving to the declaration",
112            Self::Glob => "a glob import opens the declaring module",
113            Self::ReExport => "reached through a re-export vvv followed to the declaration",
114            Self::Oracle => "syntax could not place it; an oracle that knows the code did",
115            Self::Nothing => "a bare name nothing imports, or a path vvv cannot place",
116            Self::ByName => "no declaration to judge against; matched by name",
117            Self::OtherDeclaration => "resolves to another declaration of the same name",
118            Self::External => "resolves into a crate outside the workspace",
119            Self::ImportedBy => "files whose imports lead here",
120            Self::Safe => "resolves to the declaration",
121            Self::Unverified => "nothing connects it to the declaration",
122            Self::Other => "belongs to another declaration",
123            Self::ByHand => "vvv stops short here; the change is yours to write",
124            Self::Structure => "a mod line, a modifier or a file moved",
125            Self::Rewrite => "a match and what it becomes",
126            Self::Ticked => "in the commit",
127            Self::Unticked => "left out of the commit",
128            Self::Undo => "what undo reverses",
129        }
130    }
131
132    pub fn ticked(ticked: bool) -> Self {
133        if ticked { Self::Ticked } else { Self::Unticked }
134    }
135}
136
137/// The glyph alone: `Mark::Safe` displays as `✓`.
138impl fmt::Display for Mark {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        write!(f, "{}", self.glyph())
141    }
142}
143
144impl From<Confidence> for Mark {
145    fn from(confidence: Confidence) -> Self {
146        match confidence {
147            Confidence::Resolved => Self::Safe,
148            Confidence::Unresolved => Self::Unverified,
149            Confidence::Other => Self::Other,
150        }
151    }
152}
153
154impl From<Reason> for Mark {
155    fn from(reason: Reason) -> Self {
156        match reason {
157            Reason::Declaring => Self::Declaration,
158            Reason::Imported => Self::Import,
159            Reason::Path => Self::Path,
160            Reason::Opened => Self::Glob,
161            Reason::ReExport => Self::ReExport,
162            Reason::Unresolved => Self::Nothing,
163            Reason::ByName => Self::ByName,
164            Reason::OtherDeclaration => Self::OtherDeclaration,
165            Reason::External => Self::External,
166            Reason::Oracle => Self::Oracle,
167            Reason::OracleOther => Self::OtherDeclaration,
168        }
169    }
170}
171
172/// One line naming a mutating request: `rename Config → Settings`. The only
173/// place this wording exists; titles and history lines both use it.
174pub struct IntentLine<'a>(pub &'a Intent);
175
176impl fmt::Display for IntentLine<'_> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self.0 {
179            Intent::Rewrite(i) => write!(
180                f,
181                "rewrite {} → {}",
182                i.query.pattern_str().unwrap_or_default(),
183                i.template
184            ),
185            Intent::Rename(i) => write!(f, "rename {} → {}", i.references.name, i.to),
186            Intent::Move(i) => write!(f, "move {} → {}", i.from.display(), i.to.display()),
187            Intent::MoveSymbol(i) => write!(
188                f,
189                "move {} from {} → {}",
190                i.name,
191                i.from.display(),
192                i.to.display()
193            ),
194            Intent::Batch(BatchIntent { intents }) => {
195                write!(f, "batch of {}", Plural(intents.len(), "step"))
196            }
197        }
198    }
199}
200
201/// `1 file` / `3 files` / `1 entry` / `2 entries` / `1 match` / `2 matches`.
202pub struct Plural(pub usize, pub &'static str);
203
204impl fmt::Display for Plural {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        let Plural(n, noun) = *self;
207        if n == 1 {
208            return write!(f, "1 {noun}");
209        }
210        let plural = match noun {
211            "entry" => "entries".to_owned(),
212            "match" => "matches".to_owned(),
213            other => format!("{other}s"),
214        };
215        write!(f, "{n} {plural}")
216    }
217}
218
219/// The distinct files among some paths, said as `3 files`.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub struct Files(usize);
222
223impl Files {
224    /// Count the distinct paths.
225    pub fn among<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
226        Self(paths.into_iter().collect::<BTreeSet<_>>().len())
227    }
228
229    pub const fn count(self) -> usize {
230        self.0
231    }
232}
233
234impl fmt::Display for Files {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        write!(f, "{}", Plural(self.0, "file"))
237    }
238}
239
240/// Coarse relative time: `just now`, `5 min ago`, `3 h ago`, `2 days ago`.
241pub struct Ago(u64);
242
243impl Ago {
244    pub fn now() -> u64 {
245        SystemTime::now()
246            .duration_since(UNIX_EPOCH)
247            .map_or(0, |d| d.as_secs())
248    }
249
250    pub fn between(then: u64, now: u64) -> Self {
251        Self(now.saturating_sub(then))
252    }
253}
254
255impl fmt::Display for Ago {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        match self.0 {
258            0..60 => write!(f, "just now"),
259            60..3600 => write!(f, "{} min ago", self.0 / 60),
260            3600..86400 => write!(f, "{} h ago", self.0 / 3600),
261            _ => write!(f, "{} days ago", self.0 / 86400),
262        }
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn verdicts_and_reasons_map_onto_the_vocabulary() {
272        assert_eq!(Mark::from(Confidence::Unresolved).to_string(), "?");
273        assert_eq!(Mark::from(Reason::ReExport).word(), "re-export");
274        assert_eq!(Mark::from(Reason::Path).glyph(), Mark::Import.glyph());
275        assert_eq!(Mark::ticked(true).glyph(), '▪');
276    }
277
278    #[test]
279    fn ago_buckets() {
280        assert_eq!(Ago::between(100, 130).to_string(), "just now");
281        assert_eq!(Ago::between(0, 300).to_string(), "5 min ago");
282        assert_eq!(Ago::between(0, 7200).to_string(), "2 h ago");
283        assert_eq!(Ago::between(0, 200_000).to_string(), "2 days ago");
284    }
285}