Skip to main content

vvv_core/resolve/
address.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::paths::Name;
8
9/// The name a package goes by in paths: a Rust crate's lib name (`fff`, not
10/// `fff-search`), a TypeScript package's name. The layout decides the spelling.
11#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct PackageId(String);
14
15impl PackageId {
16    pub fn new(name: impl Into<String>) -> Self {
17        Self(name.into())
18    }
19
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24
25impl From<&str> for PackageId {
26    fn from(name: &str) -> Self {
27        Self::new(name)
28    }
29}
30
31impl fmt::Display for PackageId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37/// A position in a language's namespace: the package it belongs to and the
38/// path within it — `fff :: [grep, types]` for a Rust module, path
39/// components for a TypeScript file. Prefix relations, which are what a move
40/// cares about, never hold across packages.
41#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
42pub struct Address {
43    package: PackageId,
44    path: Vec<Name>,
45}
46
47impl Address {
48    pub fn new(
49        package: impl Into<PackageId>,
50        path: impl IntoIterator<Item = impl Into<Name>>,
51    ) -> Self {
52        Self {
53            package: package.into(),
54            path: path.into_iter().map(Into::into).collect(),
55        }
56    }
57
58    /// The package itself: a crate root, a TypeScript package directory.
59    pub fn root(package: impl Into<PackageId>) -> Self {
60        Self::new(package, std::iter::empty::<Name>())
61    }
62
63    pub fn package(&self) -> &PackageId {
64        &self.package
65    }
66
67    pub fn path(&self) -> &[Name] {
68        &self.path
69    }
70
71    pub fn is_root(&self) -> bool {
72        self.path.is_empty()
73    }
74
75    pub fn starts_with(&self, prefix: &Address) -> bool {
76        self.package == prefix.package && self.path.starts_with(&prefix.path)
77    }
78
79    /// The enclosing position; `None` at a package root.
80    pub fn parent(&self) -> Option<Address> {
81        let (_, rest) = self.path.split_last()?;
82        Some(Address::new(self.package.clone(), rest.iter().cloned()))
83    }
84
85    pub fn join(&self, segment: impl Into<Name>) -> Address {
86        let mut path = self.path.clone();
87        path.push(segment.into());
88        Address {
89            package: self.package.clone(),
90            path,
91        }
92    }
93
94    pub fn extend(&self, rest: impl IntoIterator<Item = impl Into<Name>>) -> Address {
95        let mut path = self.path.clone();
96        path.extend(rest.into_iter().map(Into::into));
97        Address {
98            package: self.package.clone(),
99            path,
100        }
101    }
102
103    /// Replace the leading `from` with `to`. `None` when `self` is not under `from`.
104    pub fn rebase(&self, from: &Address, to: &Address) -> Option<Address> {
105        let rest = self.strip_prefix(from)?;
106        Some(to.extend(rest.iter().cloned()))
107    }
108
109    /// Segments after `prefix`, if `self` is under it (same package).
110    pub fn strip_prefix(&self, prefix: &Address) -> Option<&[Name]> {
111        (self.package == prefix.package)
112            .then(|| self.path.strip_prefix(prefix.path.as_slice()))
113            .flatten()
114    }
115
116    /// The deepest position both are under; `None` across packages.
117    pub fn lowest_common_ancestor(&self, other: &Address) -> Option<Address> {
118        if self.package != other.package {
119            return None;
120        }
121        let shared = self
122            .path
123            .iter()
124            .zip(&other.path)
125            .take_while(|(a, b)| a == b)
126            .count();
127        Some(Address::new(
128            self.package.clone(),
129            self.path[..shared].iter().cloned(),
130        ))
131    }
132
133    /// The path within the package, joined; the package is not shown.
134    pub fn display_with(&self, separator: &str) -> String {
135        self.path
136            .iter()
137            .map(Name::as_str)
138            .collect::<Vec<_>>()
139            .join(separator)
140    }
141}
142
143/// `package::a::b`; a nameless package (a lone TypeScript root) is left out
144/// rather than shown as a leading `::`.
145impl fmt::Display for Address {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        let mut first = self.package.as_str().is_empty();
148        if !first {
149            write!(f, "{}", self.package)?;
150        }
151        for segment in &self.path {
152            if !first {
153                f.write_str("::")?;
154            }
155            write!(f, "{segment}")?;
156            first = false;
157        }
158        Ok(())
159    }
160}
161
162/// A package a layout found: where it is and what it depends on.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct Package {
165    /// How paths name it by default.
166    pub id: PackageId,
167    /// Its name in the manifest (`fff-search`), which is how dependencies
168    /// refer to it whatever they rename it to.
169    pub name: String,
170    /// Directory holding the manifest, workspace-relative.
171    pub root: PathBuf,
172    /// What it depends on, workspace members and external packages alike.
173    #[serde(default)]
174    pub dependencies: Vec<Dependency>,
175}
176
177/// One dependency as a manifest states it: the name paths use for it, and
178/// the package that name stands for (`fff = { package = "fff-search" }`).
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180pub struct Dependency {
181    pub used_as: PackageId,
182    pub package: String,
183}
184
185/// Every package in a workspace, looked up by the deepest root containing a
186/// path or by name.
187#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
188pub struct Packages {
189    by_root: BTreeMap<PathBuf, Package>,
190}
191
192impl Packages {
193    pub fn new(packages: impl IntoIterator<Item = Package>) -> Self {
194        Self {
195            by_root: packages.into_iter().map(|p| (p.root.clone(), p)).collect(),
196        }
197    }
198
199    /// The package whose root is the deepest ancestor of `path`.
200    pub fn containing(&self, path: &Path) -> Option<&Package> {
201        path.ancestors().find_map(|dir| self.by_root.get(dir))
202    }
203
204    pub fn named(&self, id: &PackageId) -> Option<&Package> {
205        self.by_root.values().find(|p| &p.id == id)
206    }
207
208    pub fn iter(&self) -> impl Iterator<Item = &Package> {
209        self.by_root.values()
210    }
211
212    /// Whether `id` is a package of this workspace, as opposed to one it
213    /// only depends on.
214    pub fn is_member(&self, id: &PackageId) -> bool {
215        self.named(id).is_some()
216    }
217
218    /// What a path starting with `head`, written in package `from`, refers
219    /// to: a member by its own id, a member through a dependency (renamed or
220    /// not), or an external dependency under the name it is used as. `None`
221    /// when `from` does not depend on anything of that name.
222    pub fn referent(&self, from: &PackageId, head: &PackageId) -> Option<PackageId> {
223        if self.is_member(head) {
224            return Some(head.clone());
225        }
226        let dependency = self
227            .named(from)?
228            .dependencies
229            .iter()
230            .find(|d| &d.used_as == head)?;
231        Some(
232            self.iter()
233                .find(|p| p.name == dependency.package)
234                .map_or_else(|| head.clone(), |member| member.id.clone()),
235        )
236    }
237
238    /// The name package `from` uses for `target` in paths: the dependency's
239    /// key when renamed, otherwise the target's own id.
240    pub fn name_for(&self, from: &PackageId, target: &PackageId) -> PackageId {
241        let Some(member) = self.named(target) else {
242            return target.clone();
243        };
244        self.named(from)
245            .and_then(|p| p.dependencies.iter().find(|d| d.package == member.name))
246            .map_or_else(|| target.clone(), |d| d.used_as.clone())
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn rebase_replaces_prefix_only() {
256        let a = Address::new("k", ["foo", "bar", "X"]);
257        let from = Address::new("k", ["foo", "bar"]);
258        let to = Address::new("k", ["baz", "qux"]);
259        assert_eq!(
260            a.rebase(&from, &to),
261            Some(Address::new("k", ["baz", "qux", "X"]))
262        );
263        assert_eq!(a.rebase(&Address::new("k", ["nope"]), &to), None);
264    }
265
266    #[test]
267    fn nothing_holds_across_packages() {
268        let a = Address::new("a", ["m", "x"]);
269        let b = Address::new("b", ["m", "x"]);
270        assert!(!a.starts_with(&Address::root("b")));
271        assert_eq!(a.strip_prefix(&Address::root("b")), None);
272        assert_eq!(a.lowest_common_ancestor(&b), None);
273        assert_ne!(a, b);
274    }
275
276    #[test]
277    fn lowest_common_ancestor_within_a_package() {
278        let a = Address::new("k", ["grep", "types", "GrepMatch"]);
279        let b = Address::new("k", ["grep", "sink"]);
280        assert_eq!(
281            a.lowest_common_ancestor(&b),
282            Some(Address::new("k", ["grep"]))
283        );
284        assert_eq!(
285            a.lowest_common_ancestor(&Address::new("k", ["other"])),
286            Some(Address::root("k"))
287        );
288        assert_eq!(Address::root("k").parent(), None);
289    }
290
291    #[test]
292    fn packages_find_the_deepest_root() {
293        let packages = Packages::new([
294            Package {
295                id: "top".into(),
296                name: "top".into(),
297                root: PathBuf::from(""),
298                dependencies: vec![Dependency {
299                    used_as: "in".into(),
300                    package: "inner-pkg".into(),
301                }],
302            },
303            Package {
304                id: "inner_pkg".into(),
305                name: "inner-pkg".into(),
306                root: PathBuf::from("crates/inner"),
307                dependencies: Vec::new(),
308            },
309        ]);
310        assert_eq!(
311            packages
312                .containing(Path::new("crates/inner/src/lib.rs"))
313                .map(|p| p.id.as_str()),
314            Some("inner_pkg")
315        );
316        assert_eq!(
317            packages
318                .containing(Path::new("src/main.rs"))
319                .map(|p| p.id.as_str()),
320            Some("top")
321        );
322        assert_eq!(
323            packages
324                .named(&"inner_pkg".into())
325                .map(|p| p.root.as_path()),
326            Some(Path::new("crates/inner"))
327        );
328    }
329
330    #[test]
331    fn renamed_dependencies_refer_to_members_and_are_spelled_back() {
332        let packages = Packages::new([
333            Package {
334                id: "top".into(),
335                name: "top".into(),
336                root: PathBuf::from(""),
337                dependencies: vec![
338                    Dependency {
339                        used_as: "in".into(),
340                        package: "inner-pkg".into(),
341                    },
342                    Dependency {
343                        used_as: "serde".into(),
344                        package: "serde".into(),
345                    },
346                ],
347            },
348            Package {
349                id: "inner_pkg".into(),
350                name: "inner-pkg".into(),
351                root: PathBuf::from("crates/inner"),
352                dependencies: Vec::new(),
353            },
354        ]);
355        let top: PackageId = "top".into();
356        assert_eq!(
357            packages.referent(&top, &"in".into()),
358            Some("inner_pkg".into())
359        );
360        assert_eq!(
361            packages.referent(&top, &"inner_pkg".into()),
362            Some("inner_pkg".into())
363        );
364        assert_eq!(
365            packages.referent(&top, &"serde".into()),
366            Some("serde".into()),
367            "external, by its own name"
368        );
369        assert_eq!(packages.referent(&top, &"nope".into()), None);
370        assert_eq!(packages.name_for(&top, &"inner_pkg".into()), "in".into());
371        assert_eq!(
372            packages.name_for(&"inner_pkg".into(), &"top".into()),
373            "top".into()
374        );
375    }
376}