Skip to main content

submilli_engine/
mangle.rs

1//! Fully-qualified symbol naming: `<package>#<symbol>` for public/top-level
2//! package symbols. Internal module symbols use a separate `mod:` namespace so
3//! they cannot collide with package-public names. Treat [`MangledName`] as
4//! opaque; use the constructors rather than depending on the textual format.
5
6use std::fmt;
7
8use serde::{Deserialize, Serialize};
9
10pub const PRELUDE_PACKAGE: &str = "submilli:prelude";
11pub const USER_PACKAGE: &str = "main";
12pub const SEP: char = '#';
13const MODULE_PREFIX: &str = "mod:";
14
15/// Opaque newtype; construct via the module builders to keep the format centralised.
16#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17pub struct MangledName(String);
18
19impl MangledName {
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24
25impl fmt::Display for MangledName {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(&self.0)
28    }
29}
30
31impl AsRef<str> for MangledName {
32    fn as_ref(&self) -> &str {
33        &self.0
34    }
35}
36
37/// Canonical public package symbol.
38pub fn package_symbol(package: &str, symbol: &str) -> MangledName {
39    MangledName(format!("{package}{SEP}{symbol}"))
40}
41
42/// Internal module symbol for a declaration in a multi-file package. `module` is
43/// the canonicalized package-relative path (`util`, `internal/math`) — no
44/// leading `./`, no `.subm` suffix. Root-exported (public) symbols use
45/// [`package_symbol`] instead.
46pub fn package_module_symbol(package: &str, module: &str, symbol: &str) -> MangledName {
47    MangledName(format!(
48        "{MODULE_PREFIX}{package}{SEP}{module}{SEP}{symbol}"
49    ))
50}
51
52pub fn prelude(symbol: &str) -> MangledName {
53    package_symbol(PRELUDE_PACKAGE, symbol)
54}
55
56/// Whether a symbol is declared by Submilli itself (the prelude or a
57/// `submilli:` standard-library module) rather than by a program or package.
58pub fn is_builtin(name: &MangledName) -> bool {
59    let unprefixed = name
60        .as_str()
61        .strip_prefix(MODULE_PREFIX)
62        .unwrap_or(name.as_str());
63    unprefixed.starts_with("submilli:")
64}
65
66pub fn extend(parent: &MangledName, suffix: &str) -> MangledName {
67    MangledName(format!("{}{}{}", parent.as_str(), SEP, suffix))
68}
69
70/// Dispatch key for a static class member: `Class#static#name`. The extra
71/// `static` segment keeps statics disjoint from instance-method export keys
72/// (`Class#name`) — a static and an instance method may share a name.
73pub fn static_member(class: &MangledName, member: &str) -> MangledName {
74    extend(&extend(class, "static"), member)
75}
76
77/// Export key of the global that caches a function's closure, shared by every
78/// module that reads the function as a value. The angle brackets keep it apart
79/// from any source identifier.
80pub fn closure_cache(function: &MangledName) -> MangledName {
81    extend(function, "<closure>")
82}
83
84pub fn host(host_module: &str, symbol: &str) -> MangledName {
85    package_symbol(host_module, symbol)
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use std::collections::BTreeMap;
92
93    #[test]
94    fn package_symbol_shape() {
95        assert_eq!(package_symbol("main", "foo").as_str(), "main#foo");
96        assert_eq!(
97            package_symbol("submilli:uuid", "v4").as_str(),
98            "submilli:uuid#v4"
99        );
100    }
101
102    #[test]
103    fn package_module_symbol_shape() {
104        assert_eq!(
105            package_module_symbol("main", "util", "foo").as_str(),
106            "mod:main#util#foo"
107        );
108        assert_eq!(
109            package_module_symbol("@acme/stripe", "internal/math", "helper").as_str(),
110            "mod:@acme/stripe#internal/math#helper",
111        );
112    }
113
114    #[test]
115    fn package_and_module_symbols_cannot_collide() {
116        assert_ne!(
117            package_symbol("main#util", "foo"),
118            package_module_symbol("main", "util", "foo"),
119        );
120    }
121
122    #[test]
123    fn prelude_shape() {
124        assert_eq!(
125            prelude("string_concat").as_str(),
126            "submilli:prelude#string_concat"
127        );
128    }
129
130    #[test]
131    fn extend_composes_three_segments() {
132        let iface = prelude("String");
133        assert_eq!(
134            extend(&iface, "concat").as_str(),
135            "submilli:prelude#String#concat",
136        );
137    }
138
139    #[test]
140    fn host_shape() {
141        assert_eq!(
142            host("submilli:console", "log").as_str(),
143            "submilli:console#log"
144        );
145    }
146
147    #[test]
148    fn newtype_keyed_lookup() {
149        let mut map: BTreeMap<MangledName, u32> = BTreeMap::new();
150        map.insert(package_symbol("main", "foo"), 42);
151        assert_eq!(map.get(&package_symbol("main", "foo")), Some(&42));
152        assert_eq!(map.get(&package_symbol("main", "absent")), None);
153    }
154}