const ZIG_RESERVED_KEYWORDS: &[&str] = &[
"addrspace",
"align",
"allowzero",
"and",
"anyframe",
"anytype",
"asm",
"async",
"await",
"break",
"callconv",
"catch",
"comptime",
"const",
"continue",
"defer",
"else",
"enum",
"errdefer",
"error",
"export",
"extern",
"fn",
"for",
"if",
"inline",
"linksection",
"noalias",
"noinline",
"nosuspend",
"opaque",
"or",
"orelse",
"packed",
"pub",
"resume",
"return",
"struct",
"suspend",
"switch",
"test",
"threadlocal",
"try",
"union",
"unreachable",
"usingnamespace",
"var",
"volatile",
"while",
];
pub fn zig_safe_name(name: &str) -> String {
if name == "_" {
"__js_underscore".to_string()
} else if ZIG_RESERVED_KEYWORDS.contains(&name) {
format!("_{}", name)
} else {
name.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IrIdent {
pub js_name: String,
pub zig_name: String,
}
impl IrIdent {
pub fn new(js_name: &str) -> Self {
Self {
js_name: js_name.to_string(),
zig_name: zig_safe_name(js_name),
}
}
pub fn with_zig_name(js_name: &str, zig_name: String) -> Self {
Self {
js_name: js_name.to_string(),
zig_name,
}
}
}
impl std::fmt::Display for IrIdent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.zig_name)
}
}
#[derive(Debug, Clone)]
pub struct NameMangler {
counters: std::collections::HashMap<String, usize>,
shadow_scopes: Vec<std::collections::HashMap<String, String>>,
}
impl NameMangler {
pub fn new() -> Self {
Self {
counters: std::collections::HashMap::new(),
shadow_scopes: Vec::new(),
}
}
pub fn next_name(&mut self, prefix: &str) -> String {
let count = self.counters.entry(prefix.to_string()).or_insert(0);
let name = format!("{}_{}", prefix, count);
*count += 1;
name
}
pub fn peek_count(&self, prefix: &str) -> usize {
self.counters.get(prefix).copied().unwrap_or(0)
}
pub fn push_shadow_scope(&mut self) {
self.shadow_scopes.push(std::collections::HashMap::new());
}
pub fn pop_shadow_scope(&mut self) {
self.shadow_scopes.pop();
}
pub fn record_shadow(&mut self, js_name: &str, zig_name: String) {
if let Some(scope) = self.shadow_scopes.last_mut() {
scope.insert(js_name.to_string(), zig_name);
}
}
pub fn resolve_name(&self, js_name: &str) -> String {
for scope in self.shadow_scopes.iter().rev() {
if let Some(renamed) = scope.get(js_name) {
return renamed.clone();
}
}
zig_safe_name(js_name)
}
pub fn make_ident(&self, js_name: &str) -> IrIdent {
let zig_name = self.resolve_name(js_name);
IrIdent::with_zig_name(js_name, zig_name)
}
}
impl Default for NameMangler {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zig_safe_name_normal() {
assert_eq!(zig_safe_name("foo"), "foo");
}
#[test]
fn test_zig_safe_name_keyword() {
assert_eq!(zig_safe_name("return"), "_return");
assert_eq!(zig_safe_name("fn"), "_fn");
assert_eq!(zig_safe_name("try"), "_try");
}
#[test]
fn test_ir_ident_new() {
let id = IrIdent::new("myVar");
assert_eq!(id.js_name, "myVar");
assert_eq!(id.zig_name, "myVar");
}
#[test]
fn test_ir_ident_keyword() {
let id = IrIdent::new("error");
assert_eq!(id.js_name, "error");
assert_eq!(id.zig_name, "_error");
}
#[test]
fn test_zig_safe_name_underscore() {
assert_eq!(zig_safe_name("_"), "__js_underscore");
let id = IrIdent::new("_");
assert_eq!(id.js_name, "_");
assert_eq!(id.zig_name, "__js_underscore");
}
#[test]
fn test_name_mangler_sequence() {
let mut m = NameMangler::new();
assert_eq!(m.next_name("closure"), "closure_0");
assert_eq!(m.next_name("closure"), "closure_1");
assert_eq!(m.next_name("closure"), "closure_2");
assert_eq!(m.next_name("blk"), "blk_0");
}
#[test]
fn test_name_mangler_shadow() {
let mut m = NameMangler::new();
m.push_shadow_scope();
m.record_shadow("x", "x_1".to_string());
assert_eq!(m.resolve_name("x"), "x_1");
assert_eq!(m.resolve_name("y"), "y"); m.pop_shadow_scope();
assert_eq!(m.resolve_name("x"), "x"); }
#[test]
fn test_name_mangler_nested_shadow() {
let mut m = NameMangler::new();
m.push_shadow_scope();
m.record_shadow("x", "x_1".to_string());
m.push_shadow_scope();
m.record_shadow("x", "x_2".to_string());
assert_eq!(m.resolve_name("x"), "x_2"); m.pop_shadow_scope();
assert_eq!(m.resolve_name("x"), "x_1"); m.pop_shadow_scope();
assert_eq!(m.resolve_name("x"), "x"); }
#[test]
fn test_make_ident_with_shadow() {
let mut m = NameMangler::new();
m.push_shadow_scope();
m.record_shadow("type", "type_1".to_string());
let id = m.make_ident("type");
assert_eq!(id.js_name, "type");
assert_eq!(id.zig_name, "type_1"); }
}