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/// The member name of a host-implemented property's setter, `@set:<property>`.
71/// Codegen lowers `receiver.property = value` on a prelude interface to a call
72/// of `<iface>#@set:<property>` when the prelude declares one.
73pub fn property_setter(property: &str) -> String {
74    format!("@set:{property}")
75}
76
77/// Dispatch key for a static class member: `Class#static#name`. The extra
78/// `static` segment keeps statics disjoint from instance-method export keys
79/// (`Class#name`) — a static and an instance method may share a name.
80pub fn static_member(class: &MangledName, member: &str) -> MangledName {
81    extend(&extend(class, "static"), member)
82}
83
84/// Export key of the global that caches a function's closure, shared by every
85/// module that reads the function as a value. The angle brackets keep it apart
86/// from any source identifier.
87pub fn closure_cache(function: &MangledName) -> MangledName {
88    extend(function, "<closure>")
89}
90
91pub fn host(host_module: &str, symbol: &str) -> MangledName {
92    package_symbol(host_module, symbol)
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use std::collections::BTreeMap;
99
100    #[test]
101    fn package_symbol_shape() {
102        assert_eq!(package_symbol("main", "foo").as_str(), "main#foo");
103        assert_eq!(
104            package_symbol("submilli:uuid", "v4").as_str(),
105            "submilli:uuid#v4"
106        );
107    }
108
109    #[test]
110    fn package_module_symbol_shape() {
111        assert_eq!(
112            package_module_symbol("main", "util", "foo").as_str(),
113            "mod:main#util#foo"
114        );
115        assert_eq!(
116            package_module_symbol("@pied-piper/stripe", "internal/math", "helper").as_str(),
117            "mod:@pied-piper/stripe#internal/math#helper",
118        );
119    }
120
121    #[test]
122    fn package_and_module_symbols_cannot_collide() {
123        assert_ne!(
124            package_symbol("main#util", "foo"),
125            package_module_symbol("main", "util", "foo"),
126        );
127    }
128
129    #[test]
130    fn prelude_shape() {
131        assert_eq!(
132            prelude("string_concat").as_str(),
133            "submilli:prelude#string_concat"
134        );
135    }
136
137    #[test]
138    fn extend_composes_three_segments() {
139        let iface = prelude("String");
140        assert_eq!(
141            extend(&iface, "concat").as_str(),
142            "submilli:prelude#String#concat",
143        );
144    }
145
146    #[test]
147    fn host_shape() {
148        assert_eq!(
149            host("submilli:console", "log").as_str(),
150            "submilli:console#log"
151        );
152    }
153
154    #[test]
155    fn newtype_keyed_lookup() {
156        let mut map: BTreeMap<MangledName, u32> = BTreeMap::new();
157        map.insert(package_symbol("main", "foo"), 42);
158        assert_eq!(map.get(&package_symbol("main", "foo")), Some(&42));
159        assert_eq!(map.get(&package_symbol("main", "absent")), None);
160    }
161}