Skip to main content

js2zig_core/
builtins.rs

1use crate::host::HostFnRegistry;
2use crate::infer::ZigType;
3use std::collections::HashMap;
4
5/// Result of looking up a JS built-in call
6#[derive(Debug, Clone)]
7pub struct BuiltinTranslation {
8    /// The Zig code template, {} placeholders for arguments
9    pub template: String,
10    /// Return type of the builtin function (if known)
11    pub return_type: Option<crate::infer::ZigType>,
12}
13
14impl BuiltinTranslation {
15    /// Create a new BuiltinTranslation with template only (return type unknown).
16    pub fn new(template: String) -> Self {
17        Self {
18            template,
19            return_type: None,
20        }
21    }
22
23    /// Create a new BuiltinTranslation with known return type.
24    pub fn with_return_type(template: String, return_type: crate::infer::ZigType) -> Self {
25        Self {
26            template,
27            return_type: Some(return_type),
28        }
29    }
30}
31
32/// Central registry for JS → Zig built-in mappings
33pub struct BuiltinRegistry {
34    /// Method calls: key = "object.method" → template
35    methods: HashMap<String, BuiltinTranslation>,
36    /// Global function calls: key = "functionName" → template
37    globals: HashMap<String, BuiltinTranslation>,
38    /// Static property access: key = "object.property" → template
39    properties: HashMap<String, String>,
40}
41
42impl BuiltinRegistry {
43    pub fn new() -> Self {
44        let mut registry = Self {
45            methods: HashMap::new(),
46            globals: HashMap::new(),
47            properties: HashMap::new(),
48        };
49
50        // ── Math constants (static properties) ──
51        registry.add_property("Math", "PI", "std.math.pi");
52        registry.add_property("Math", "E", "std.math.e");
53
54        // ── Tier 1: Direct Zig builtins ──
55        registry.add_method("Math", "abs", "@abs({})");
56        registry.add_method("Math", "ceil", "@ceil({})");
57        registry.add_method("Math", "floor", "@floor({})");
58        registry.add_method("Math", "trunc", "@trunc({})");
59        registry.add_method("Math", "round", "@round({})");
60        registry.add_method("Math", "sqrt", "@sqrt({})");
61        registry.add_method("Math", "cbrt", "@sqrt(@sqrt({}))"); // approximation
62        registry.add_method("Math", "sin", "@sin({})");
63        registry.add_method("Math", "cos", "@cos({})");
64        registry.add_method("Math", "tan", "@tan({})");
65        registry.add_method("Math", "asin", "@asin({})");
66        registry.add_method("Math", "acos", "@acos({})");
67        registry.add_method("Math", "atan", "@atan({})");
68        registry.add_method("Math", "atan2", "@atan2({}, {})");
69        registry.add_method("Math", "exp", "@exp({})");
70        registry.add_method("Math", "log", "@log({})");
71        registry.add_method("Math", "log2", "@log2({})");
72        registry.add_method("Math", "log10", "@log10({})");
73        registry.add_method("Math", "min", "@min({}, {})");
74        registry.add_method("Math", "max", "@max({}, {})");
75        registry.add_method("Math", "sign", "if ({0} > 0) @as(i64, 1) else if ({0} < 0) @as(i64, -1) else @as(i64, 0)");
76        registry.add_method("Math", "hypot", "@sqrt({0} * {0} + {1} * {1})");
77
78        // ── Tier 2: std lib ──
79        registry.add_method("Math", "pow", "std.math.pow(f64, {}, {})");
80        registry.add_method(
81            "Math", "random",
82            "std.crypto.random.float(f64)",
83        );
84
85        // Global functions (Tier 2)
86        registry.add_global("parseInt", "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)");
87        registry.add_global("parseFloat", "std.fmt.parseFloat(f64, {}) catch @as(f64, 0.0)");
88        registry.add_global("isNaN", "std.math.isNan(@as(f64, {}))");
89        registry.add_global("isFinite", "!std.math.isInf({})");
90        registry.add_global("Number", "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)");
91
92        // ── Tier 3: URI encoding ──
93        registry.add_global("encodeURIComponent", "js_uri.encodeURIComponent(js_allocator.g_alloc(), {})");
94        registry.add_global("decodeURIComponent", "js_uri.decodeURIComponent(js_allocator.g_alloc(), {})");
95
96        // ── Tier 3: Runtime ──
97        // All runtime functions use js_allocator.g_alloc() where Zig needs an allocator.
98        // For type-dispatched methods, {} is sequential: {0}=receiver, {1}=arg0, {2}=arg1, ...
99        // String methods
100        registry.add_method("String", "length", "{}.len");
101        registry.add_method_runtime("string", "length", "{}.len", "js_string");
102        registry.add_method_runtime("string", "toUpperCase", "(js_string.toUpper(js_allocator.g_alloc(), {}) catch \"\")", "js_string");
103        registry.add_method_runtime("string", "toLowerCase", "(js_string.toLower(js_allocator.g_alloc(), {}) catch \"\")", "js_string");
104        registry.add_method_runtime("string", "charAt", "(js_string.charAt(js_allocator.g_alloc(), {}, {}) catch \"\")", "js_string");
105        registry.add_method_runtime("string", "charCodeAt", "{0}[@intCast({1})]", "js_string");
106        registry.add_method_runtime("string", "concat", "(js_string.concat(js_allocator.g_alloc(), {}, {}) catch \"\")", "js_string");
107        registry.add_method_runtime("string", "includes", "js_string.includes({}, {})", "js_string");
108        registry.add_method_runtime("string", "indexOf", "js_string.indexOf({}, {})", "js_string");
109        registry.add_method_runtime("string", "startsWith", "js_string.startsWith({}, {})", "js_string");
110        registry.add_method_runtime("string", "endsWith", "js_string.endsWith({}, {})", "js_string");
111        registry.add_method_runtime("string", "slice", "js_string.slice({}, {}, {})", "js_string");
112        registry.add_method_runtime("string", "split", "(js_string.split(js_allocator.g_alloc(), {}, {}) catch &[_][]const u8{})", "js_string");
113        registry.add_method_runtime("string", "replace", "(js_string.replace(js_allocator.g_alloc(), {}, {}, {}) catch \"\")", "js_string");
114        registry.add_method_runtime("string", "trim", "js_string.trim({})", "js_string");
115        registry.add_method_runtime("string", "repeat", "(js_string.repeat(js_allocator.g_alloc(), {}, {}) catch \"\")", "js_string");
116
117        // Console
118        registry.add_method_runtime("console", "log", "js_console.log({})", "js_console");
119        registry.add_method_runtime("console", "error", "js_console.err({})", "js_console");
120        registry.add_method_runtime("console", "warn", "js_console.warn({})", "js_console");
121
122        // JSON
123        registry.add_method_runtime("JSON", "stringify", "js_json.stringifyI64({})", "js_json");
124        registry.add_method_runtime("JSON", "parse", "js_json.parse({})", "js_json");
125
126        // Array
127        registry.add_method_runtime("Array", "isArray", "js_array.isArray({})", "js_array");
128        registry.add_method_runtime("array", "length", "{}.len", "js_array");
129        registry.add_method_runtime("array", "push", "(js_array.push(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})", "js_array");
130        registry.add_method_runtime("array", "pop", "js_array.pop({})", "js_array");
131        registry.add_method_runtime("array", "shift", "js_array.shift({})", "js_array");
132        registry.add_method_runtime("array", "unshift", "(js_array.unshift(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})", "js_array");
133        registry.add_method_runtime("array", "join", "(js_array.join(js_allocator.g_alloc(), {}, {}) catch \"\")", "js_array");
134        registry.add_method_runtime("array", "map", "(js_array.map(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})", "js_array");
135        registry.add_method_runtime("array", "filter", "(js_array.filter(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})", "js_array");
136        registry.add_method_runtime("array", "indexOf", "js_array.indexOf({}, {})", "js_array");
137        registry.add_method_runtime("array", "includes", "js_array.includes({}, {})", "js_array");
138        registry.add_method_runtime("array", "reverse", "(js_array.reverse(js_allocator.g_alloc(), {}) catch &[_]i64{})", "js_array");
139        registry.add_method_runtime("array", "slice", "js_array.slice({}, {}, {})", "js_array");
140        registry.add_method_runtime("array", "concat", "(js_array.concat(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})", "js_array");
141        registry.add_method_runtime("array", "sort", "(js_array.sort(js_allocator.g_alloc(), {}) catch &[_]i64{})", "js_array");
142
143        // ── Tier 3: Object ──
144        registry.add_method_runtime("Object", "keys", "js_object.keys(js_allocator.g_alloc(), {})", "js_object");
145        registry.add_method_runtime("Object", "values", "js_object.values(js_allocator.g_alloc(), {})", "js_object");
146        registry.add_method_runtime("Object", "assign", "js_object.assign({}, {})", "js_object");
147        registry.add_method_runtime("Object", "entries", "js_object.entries(js_allocator.g_alloc(), {})", "js_object");
148
149        // ── Tier 3: Number ──
150        registry.add_method_runtime("Number", "isNaN", "js_number.isNaN(@as(f64, @floatFromInt({})))", "js_number");
151        registry.add_method_runtime("Number", "isFinite", "js_number.isFinite(@as(f64, @floatFromInt({})))", "js_number");
152        registry.add_method_runtime("Number", "isInteger", "js_number.isInteger(@as(f64, @floatFromInt({})))", "js_number");
153        registry.add_method_runtime("Number", "parseInt", "js_number.parseInt({})", "js_number");
154        registry.add_method_runtime("Number", "parseFloat", "js_number.parseFloat({})", "js_number");
155
156        // ── Tier 3: Boolean ──
157        registry.add_method_runtime("Boolean", "toString", "if ({}) \"true\" else \"false\"", "js_number");
158
159        // ── Tier 3: Date ──
160        registry.add_method_runtime("Date", "now", "js_date.now()", "js_date");
161        registry.add_method_runtime("Date", "getTime", "js_date.getTime({})", "js_date");
162        registry.add_method_runtime("Date", "getFullYear", "js_date.getFullYear({})", "js_date");
163        registry.add_method_runtime("Date", "getMonth", "js_date.getMonth({})", "js_date");
164        registry.add_method_runtime("Date", "getDate", "js_date.getDate({})", "js_date");
165        registry.add_method_runtime("Date", "getDay", "js_date.getDay({})", "js_date");
166        registry.add_method_runtime("Date", "getHours", "js_date.getHours({})", "js_date");
167        registry.add_method_runtime("Date", "getMinutes", "js_date.getMinutes({})", "js_date");
168        registry.add_method_runtime("Date", "getSeconds", "js_date.getSeconds({})", "js_date");
169        registry.add_method_runtime("Date", "parse", "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)", "js_date");
170
171        // ── Tier 3: Map (instance methods) ──
172        registry.add_method_runtime("map", "get", "{0}.get({1})", "js_map");
173        registry.add_method_runtime("map", "set", "{0}.set({1}, {2}) catch unreachable", "js_map");
174        registry.add_method_runtime("map", "has", "{0}.has({1})", "js_map");
175        registry.add_method_runtime("map", "delete", "{0}.delete({1})", "js_map");
176        registry.add_method_runtime("map", "clear", "{0}.clear()", "js_map");
177
178        // ── Tier 3: Set (instance methods) ──
179        registry.add_method_runtime("set", "add", "{0}.add({1}) catch unreachable", "js_set");
180        registry.add_method_runtime("set", "has", "{0}.has({1})", "js_set");
181        registry.add_method_runtime("set", "delete", "{0}.delete({1})", "js_set");
182        registry.add_method_runtime("set", "clear", "{0}.clear()", "js_set");
183
184        // ── Tier 3: RegExp ──
185        registry.add_method_runtime("RegExp", "test", "js_regexp.test_({}, {})", "js_regexp");
186        registry.add_method_runtime("RegExp", "exec", "js_regexp.exec(js_allocator.g_alloc(), {}, {})", "js_regexp");
187
188        // ── Tier 4: Rust via C ABI (reserved for custom host functions) ──
189
190        registry
191    }
192
193    /// Register host functions from a HostFnRegistry so they can be called
194    /// from JS code. These functions are defined in Rust with `#[no_mangle] pub extern "C"`.
195    ///
196    /// For functions with string params/returns, the template calls the `_wrap` variant
197    /// (generated in host.zig) which handles `[]const u8` ↔ `[*:0]const u8` conversion.
198    pub fn register_host_fns(&mut self, host_fns: &HostFnRegistry) {
199        for def in host_fns.sync_fns() {
200            // Build the template: host.fnName(arg1, arg2, ...)
201            let args: String = (0..def.params.len())
202                .map(|i| format!("{{{}}}", i))
203                .collect::<Vec<_>>()
204                .join(", ");
205
206            // Check if this function needs the string conversion wrapper
207            let has_string = def.params.iter().any(|(_, t)| *t == ZigType::String)
208                || def.ret_type == ZigType::String;
209            let fn_name = if has_string {
210                format!("{}_wrap", def.name)
211            } else {
212                def.name.clone()
213            };
214            let template = format!("host.{}({})", fn_name, args);
215
216            // Store return type
217            let return_type = def.ret_type.clone();
218
219            self.globals.insert(
220                def.name.clone(),
221                BuiltinTranslation::with_return_type(template, return_type),
222            );
223        }
224    }
225
226    fn add_method(&mut self, object: &str, method: &str, template: &str) {
227        let key = format!("{}.{}", object, method);
228        self.methods.insert(key, BuiltinTranslation::new(template.to_string()));
229    }
230
231    fn add_method_runtime(&mut self, object: &str, method: &str, template: &str, _dep: &str) {
232        self.add_method(object, method, template);
233    }
234
235    fn add_global(&mut self, name: &str, template: &str) {
236        self.globals.insert(name.to_string(), BuiltinTranslation::new(template.to_string()));
237    }
238
239    fn add_property(&mut self, object: &str, property: &str, zig_expr: &str) {
240        let key = format!("{}.{}", object, property);
241        self.properties.insert(key, zig_expr.to_string());
242    }
243
244    /// Look up a method call: `object.method(...)` → Zig translation
245    pub fn lookup_method(&self, object: &str, method: &str) -> Option<&BuiltinTranslation> {
246        let key = format!("{}.{}", object, method);
247        self.methods.get(&key)
248    }
249
250    /// Look up a global function call: `func(...)` → Zig translation
251    pub fn lookup_global(&self, name: &str) -> Option<&BuiltinTranslation> {
252        self.globals.get(name)
253    }
254
255    /// Look up the return type of a global function (if known).
256    pub fn lookup_global_return_type(&self, name: &str) -> Option<&crate::infer::ZigType> {
257        self.globals.get(name).and_then(|trans| trans.return_type.as_ref())
258    }
259
260    /// Look up a static property: `Obj.prop` → Zig expression
261    pub fn lookup_property(&self, object: &str, property: &str) -> Option<&str> {
262        let key = format!("{}.{}", object, property);
263        self.properties.get(&key).map(|s| s.as_str())
264    }
265
266}
267
268impl Default for BuiltinRegistry {
269    fn default() -> Self {
270        Self::new()
271    }
272}