Skip to main content

js2zig_core/zigir/
ident.rs

1// zigir/ident.rs
2// IR identifier + name mangling.
3
4/// Zig reserved keywords that JS identifiers might collide with.
5/// Pre-pends `_` to avoid collisions.
6const ZIG_RESERVED_KEYWORDS: &[&str] = &[
7    "addrspace",
8    "align",
9    "allowzero",
10    "and",
11    "anyframe",
12    "anytype",
13    "asm",
14    "async",
15    "await",
16    "break",
17    "callconv",
18    "catch",
19    "comptime",
20    "const",
21    "continue",
22    "defer",
23    "else",
24    "enum",
25    "errdefer",
26    "error",
27    "export",
28    "extern",
29    "fn",
30    "for",
31    "if",
32    "inline",
33    "linksection",
34    "noalias",
35    "noinline",
36    "nosuspend",
37    "opaque",
38    "or",
39    "orelse",
40    "packed",
41    "pub",
42    "resume",
43    "return",
44    "struct",
45    "suspend",
46    "switch",
47    "test",
48    "threadlocal",
49    "try",
50    "union",
51    "unreachable",
52    "usingnamespace",
53    "var",
54    "volatile",
55    "while",
56];
57
58/// Convert a JS identifier to a Zig-safe identifier.
59/// Pre-pends `_` to avoid collisions with Zig reserved keywords.
60/// Also escapes `_` (Zig discard identifier) to `__js_underscore`.
61pub fn zig_safe_name(name: &str) -> String {
62    if name == "_" {
63        "__js_underscore".to_string()
64    } else if ZIG_RESERVED_KEYWORDS.contains(&name) {
65        format!("_{}", name)
66    } else {
67        name.to_string()
68    }
69}
70
71/// IR identifier — stores both the original JS name and the escaped Zig name.
72#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub struct IrIdent {
74    /// Original JS name (for diagnostics / source mapping).
75    pub js_name: String,
76    /// Escaped Zig name (keyword-safe, shadow-renamed).
77    pub zig_name: String,
78}
79
80impl IrIdent {
81    /// Create a new IrIdent with automatic keyword escaping (no shadow rename).
82    pub fn new(js_name: &str) -> Self {
83        Self {
84            js_name: js_name.to_string(),
85            zig_name: zig_safe_name(js_name),
86        }
87    }
88
89    /// Create an IrIdent with an explicit Zig name (already escaped/renamed).
90    pub fn with_zig_name(js_name: &str, zig_name: String) -> Self {
91        Self {
92            js_name: js_name.to_string(),
93            zig_name,
94        }
95    }
96}
97
98impl std::fmt::Display for IrIdent {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(f, "{}", self.zig_name)
101    }
102}
103
104/// Name mangling counter + shadow rename manager.
105/// Generates unique identifiers for closures, labels, blocks, etc.
106#[derive(Debug, Clone)]
107pub struct NameMangler {
108    /// Counter per prefix: "closure" → 0, "arrow" → 0, "blk" → 0, etc.
109    counters: std::collections::HashMap<String, usize>,
110    /// Shadow renaming stack: each scope level has a map JS-name → renamed Zig-name.
111    shadow_scopes: Vec<std::collections::HashMap<String, String>>,
112}
113
114impl NameMangler {
115    pub fn new() -> Self {
116        Self {
117            counters: std::collections::HashMap::new(),
118            shadow_scopes: Vec::new(),
119        }
120    }
121
122    /// Generate the next unique name for a given prefix.
123    /// Always includes a counter: `"{prefix}_0"`, `"{prefix}_1"`, `"{prefix}_2"`, etc.
124    /// This uses the standard naming convention (e.g., `_js_dest_0`, `_js_dest_1`).
125    pub fn next_name(&mut self, prefix: &str) -> String {
126        let count = self.counters.entry(prefix.to_string()).or_insert(0);
127        let name = format!("{}_{}", prefix, count);
128        *count += 1;
129        name
130    }
131
132    /// Peek at the current counter value for a prefix (does not increment).
133    pub fn peek_count(&self, prefix: &str) -> usize {
134        self.counters.get(prefix).copied().unwrap_or(0)
135    }
136
137    /// Push a new shadowing scope onto the rename stack.
138    pub fn push_shadow_scope(&mut self) {
139        self.shadow_scopes.push(std::collections::HashMap::new());
140    }
141
142    /// Pop the innermost shadowing scope from the rename stack.
143    pub fn pop_shadow_scope(&mut self) {
144        self.shadow_scopes.pop();
145    }
146
147    /// Record a shadow rename in the current scope.
148    pub fn record_shadow(&mut self, js_name: &str, zig_name: String) {
149        if let Some(scope) = self.shadow_scopes.last_mut() {
150            scope.insert(js_name.to_string(), zig_name);
151        }
152    }
153
154    /// Resolve a JS identifier through the shadow scope stack.
155    /// Returns the Zig-safe name, checking shadow renames from innermost to outermost.
156    pub fn resolve_name(&self, js_name: &str) -> String {
157        for scope in self.shadow_scopes.iter().rev() {
158            if let Some(renamed) = scope.get(js_name) {
159                return renamed.clone();
160            }
161        }
162        zig_safe_name(js_name)
163    }
164
165    /// Create an IrIdent for the given JS name, applying shadow renaming.
166    pub fn make_ident(&self, js_name: &str) -> IrIdent {
167        let zig_name = self.resolve_name(js_name);
168        IrIdent::with_zig_name(js_name, zig_name)
169    }
170}
171
172impl Default for NameMangler {
173    fn default() -> Self {
174        Self::new()
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn test_zig_safe_name_normal() {
184        assert_eq!(zig_safe_name("foo"), "foo");
185    }
186
187    #[test]
188    fn test_zig_safe_name_keyword() {
189        assert_eq!(zig_safe_name("return"), "_return");
190        assert_eq!(zig_safe_name("fn"), "_fn");
191        assert_eq!(zig_safe_name("try"), "_try");
192    }
193
194    #[test]
195    fn test_ir_ident_new() {
196        let id = IrIdent::new("myVar");
197        assert_eq!(id.js_name, "myVar");
198        assert_eq!(id.zig_name, "myVar");
199    }
200
201    #[test]
202    fn test_ir_ident_keyword() {
203        let id = IrIdent::new("error");
204        assert_eq!(id.js_name, "error");
205        assert_eq!(id.zig_name, "_error");
206    }
207
208    #[test]
209    fn test_zig_safe_name_underscore() {
210        assert_eq!(zig_safe_name("_"), "__js_underscore");
211        let id = IrIdent::new("_");
212        assert_eq!(id.js_name, "_");
213        assert_eq!(id.zig_name, "__js_underscore");
214    }
215
216    #[test]
217    fn test_name_mangler_sequence() {
218        let mut m = NameMangler::new();
219        assert_eq!(m.next_name("closure"), "closure_0");
220        assert_eq!(m.next_name("closure"), "closure_1");
221        assert_eq!(m.next_name("closure"), "closure_2");
222        // Different prefix starts fresh
223        assert_eq!(m.next_name("blk"), "blk_0");
224    }
225
226    #[test]
227    fn test_name_mangler_shadow() {
228        let mut m = NameMangler::new();
229        m.push_shadow_scope();
230        m.record_shadow("x", "x_1".to_string());
231        assert_eq!(m.resolve_name("x"), "x_1");
232        assert_eq!(m.resolve_name("y"), "y"); // not shadowed
233        m.pop_shadow_scope();
234        assert_eq!(m.resolve_name("x"), "x"); // scope gone
235    }
236
237    #[test]
238    fn test_name_mangler_nested_shadow() {
239        let mut m = NameMangler::new();
240        m.push_shadow_scope();
241        m.record_shadow("x", "x_1".to_string());
242        m.push_shadow_scope();
243        m.record_shadow("x", "x_2".to_string());
244        assert_eq!(m.resolve_name("x"), "x_2"); // innermost wins
245        m.pop_shadow_scope();
246        assert_eq!(m.resolve_name("x"), "x_1"); // back to outer
247        m.pop_shadow_scope();
248        assert_eq!(m.resolve_name("x"), "x"); // original
249    }
250
251    #[test]
252    fn test_make_ident_with_shadow() {
253        let mut m = NameMangler::new();
254        m.push_shadow_scope();
255        m.record_shadow("type", "type_1".to_string());
256        let id = m.make_ident("type");
257        assert_eq!(id.js_name, "type");
258        assert_eq!(id.zig_name, "type_1"); // shadow overrides keyword escaping
259    }
260}