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