Skip to main content

vvv_engine/protocol/
reach.rs

1//! Who may name a declaration, computed from its modifier and its module.
2
3use serde::{Deserialize, Serialize};
4use vvv_core::{Address, PackageId, ReachKind};
5
6/// The set of modules that may name a declaration: a kind applied to the
7/// declaring module's address. Never declared, always computed.
8#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
9#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
10#[serde(rename_all = "snake_case")]
11pub enum Reach {
12    Within(Address),
13    Package(PackageId),
14    Everyone,
15}
16
17impl Reach {
18    /// `kind` applied to `declaring`. A `Path` kind needs its module
19    /// resolved by the caller; unresolved, it is treated as the declaring
20    /// module, the narrowest reading.
21    pub fn of(kind: ReachKind, declaring: &Address, path: Option<Address>) -> Self {
22        match kind {
23            ReachKind::Declaring => Self::Within(declaring.clone()),
24            ReachKind::Parent => {
25                Self::Within(declaring.parent().unwrap_or_else(|| declaring.clone()))
26            }
27            ReachKind::Package => Self::Package(declaring.package().clone()),
28            ReachKind::Everyone => Self::Everyone,
29            ReachKind::Path => Self::Within(path.unwrap_or_else(|| declaring.clone())),
30        }
31    }
32
33    /// The narrowest kind real code writes that admits every consumer of a
34    /// declaration in `declaring`: the parent when they all sit under it,
35    /// else the package; another package means `pub`, which is never
36    /// inferred.
37    pub fn narrowest(declaring: &Address, consumers: &[Address]) -> ReachKind {
38        let mut lca = declaring.clone();
39        for consumer in consumers {
40            match lca.lowest_common_ancestor(consumer) {
41                Some(shared) => lca = shared,
42                None => return ReachKind::Everyone,
43            }
44        }
45        if Some(&lca) == declaring.parent().as_ref() {
46            ReachKind::Parent
47        } else if &lca == declaring {
48            ReachKind::Declaring
49        } else {
50            ReachKind::Package
51        }
52    }
53
54    /// Whether every module `other` admits, this reach admits too.
55    pub fn covers(&self, other: &Reach) -> bool {
56        match (self, other) {
57            (Self::Everyone, _) => true,
58            (Self::Package(p), Self::Package(q)) => p == q,
59            (Self::Package(p), Self::Within(a)) => a.package() == p,
60            (Self::Within(a), Self::Within(b)) => b.starts_with(a),
61            _ => false,
62        }
63    }
64
65    /// Whether code in module `from` may name the declaration.
66    pub fn admits(&self, from: &Address) -> bool {
67        match self {
68            Self::Within(module) => from.starts_with(module),
69            Self::Package(package) => from.package() == package,
70            Self::Everyone => true,
71        }
72    }
73}
74
75impl std::fmt::Display for Reach {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::Within(module) if module.is_root() => write!(f, "{} (root)", module.package()),
79            Self::Within(module) => write!(f, "within {module}"),
80            Self::Package(package) => write!(f, "package {package}"),
81            Self::Everyone => f.write_str("everyone"),
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn reach_admits_by_prefix_package_or_everyone() {
92        let declaring = Address::new("k", ["a", "b"]);
93        let sibling = Address::new("k", ["a", "c"]);
94        let child = Address::new("k", ["a", "b", "d"]);
95        let elsewhere = Address::new("other", ["a", "b"]);
96        let private = Reach::of(ReachKind::Declaring, &declaring, None);
97        assert!(private.admits(&child) && !private.admits(&sibling));
98        let parent = Reach::of(ReachKind::Parent, &declaring, None);
99        assert!(parent.admits(&sibling) && !parent.admits(&Address::root("k")));
100        let package = Reach::of(ReachKind::Package, &declaring, None);
101        assert!(package.admits(&Address::root("k")) && !package.admits(&elsewhere));
102        assert!(Reach::of(ReachKind::Everyone, &declaring, None).admits(&elsewhere));
103        assert_eq!(
104            Reach::of(ReachKind::Parent, &Address::root("k"), None),
105            Reach::Within(Address::root("k"))
106        );
107    }
108}