Skip to main content

js2zig_core/
builtins.rs

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