Skip to main content

vvv_core/
semantics.rs

1//! What a language's syntax means: the table that gives facts their sense.
2//!
3//! Grammar says what the tree calls things; semantics says what they do —
4//! whether importing a module scopes its names, which declarations a path
5//! can reach, what each visibility modifier lets see the declaration. All
6//! data: a language module contributes one `Semantics` beside its `Grammar`.
7
8use serde::{Deserialize, Serialize};
9
10use crate::symbol::SymbolKind;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Semantics {
14    /// Whether importing a module brings its names into scope on its own.
15    /// `false` for Rust (`use a::b;` scopes `b`, not `b::X`; only `use
16    /// a::b::*` does); `true` where the import grammar hides which names
17    /// are taken, as with `import { X } from './b'` today.
18    pub import_scopes_names: bool,
19    /// Declarations a path can reach — structs, functions, modules. Methods,
20    /// fields and variants are reached through a type, which syntax alone
21    /// cannot follow, so only these can be a rename's target.
22    pub addressable: &'static [SymbolKind],
23    /// Each visibility modifier and what it lets see the declaration.
24    pub visibility: &'static [VisibilityRule],
25    /// What a declaration without a modifier lets see it.
26    pub default_visibility: ReachKind,
27}
28
29impl Semantics {
30    pub fn is_addressable(&self, kind: SymbolKind) -> bool {
31        self.addressable.contains(&kind)
32    }
33
34    /// The reach a modifier grants, or the default when there is none.
35    pub fn reach_kind(&self, modifier: Option<&str>) -> ReachKind {
36        let Some(text) = modifier else {
37            return self.default_visibility;
38        };
39        self.visibility
40            .iter()
41            .find(|rule| rule.matches(text))
42            .map_or(self.default_visibility, |rule| rule.reach)
43    }
44}
45
46/// "The modifier spelled `text` grants `reach`." Rules are tried in order.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct VisibilityRule {
49    pub text: &'static str,
50    pub reach: ReachKind,
51    /// Match by prefix (`pub(in` for `pub(in a::b)`) rather than exactly.
52    pub prefix: bool,
53}
54
55impl VisibilityRule {
56    pub const fn exact(text: &'static str, reach: ReachKind) -> Self {
57        Self {
58            text,
59            reach,
60            prefix: false,
61        }
62    }
63
64    pub const fn prefix(text: &'static str, reach: ReachKind) -> Self {
65        Self {
66            text,
67            reach,
68            prefix: true,
69        }
70    }
71
72    fn matches(&self, modifier: &str) -> bool {
73        if self.prefix {
74            modifier.starts_with(self.text)
75        } else {
76            modifier == self.text
77        }
78    }
79}
80
81/// What a visibility modifier means, relative to the declaring module.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
83#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
84#[serde(rename_all = "snake_case")]
85pub enum ReachKind {
86    /// The declaring module and its descendants (Rust private).
87    Declaring,
88    /// The parent module and its descendants (`pub(super)`).
89    Parent,
90    /// The whole package (`pub(crate)`).
91    Package,
92    /// Everyone (`pub`, `export`).
93    Everyone,
94    /// A module named in the modifier (`pub(in a::b)`); the layout resolves it.
95    Path,
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    const RUST: Semantics = Semantics {
103        import_scopes_names: false,
104        addressable: &[SymbolKind::Struct],
105        visibility: &[
106            VisibilityRule::exact("pub", ReachKind::Everyone),
107            VisibilityRule::exact("pub(crate)", ReachKind::Package),
108            VisibilityRule::exact("pub(super)", ReachKind::Parent),
109            VisibilityRule::exact("pub(self)", ReachKind::Declaring),
110            VisibilityRule::prefix("pub(in", ReachKind::Path),
111        ],
112        default_visibility: ReachKind::Declaring,
113    };
114
115    #[test]
116    fn modifiers_map_to_reach_kinds() {
117        assert_eq!(RUST.reach_kind(None), ReachKind::Declaring);
118        assert_eq!(RUST.reach_kind(Some("pub")), ReachKind::Everyone);
119        assert_eq!(RUST.reach_kind(Some("pub(super)")), ReachKind::Parent);
120        assert_eq!(RUST.reach_kind(Some("pub(in crate::a)")), ReachKind::Path);
121        assert_eq!(
122            RUST.reach_kind(Some("pub(weird)")),
123            ReachKind::Declaring,
124            "unknown: narrowest"
125        );
126    }
127}