Skip to main content

js2zig_core/
builtins.rs

1use crate::host::HostFnRegistry;
2use crate::native_proto::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::native_proto::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::native_proto::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(
76            "Math",
77            "sign",
78            "if ({0} > 0) @as(i64, 1) else if ({0} < 0) @as(i64, -1) else @as(i64, 0)",
79        );
80        registry.add_method("Math", "hypot", "@sqrt({0} * {0} + {1} * {1})");
81
82        // ── Tier 2: std lib ──
83        registry.add_method("Math", "pow", "std.math.pow(f64, {}, {})");
84        registry.add_method("Math", "random", "std.crypto.random.float(f64)");
85
86        // Global functions (Tier 2)
87        registry.add_global(
88            "parseInt",
89            "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)",
90        );
91        registry.add_global(
92            "parseFloat",
93            "std.fmt.parseFloat(f64, {}) catch @as(f64, 0.0)",
94        );
95        registry.add_global("isNaN", "std.math.isNan(@as(f64, {}))");
96        registry.add_global("isFinite", "!std.math.isInf({})");
97        registry.add_global("Number", "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)");
98
99        // ── Tier 3: URI encoding ──
100        registry.add_global(
101            "encodeURIComponent",
102            "js_uri.encodeURIComponent(js_allocator.g_alloc(), {})",
103        );
104        registry.add_global(
105            "decodeURIComponent",
106            "js_uri.decodeURIComponent(js_allocator.g_alloc(), {})",
107        );
108
109        // ── Tier 3: Runtime ──
110        // All runtime functions use js_allocator.g_alloc() where Zig needs an allocator.
111        // For type-dispatched methods, {} is sequential: {0}=receiver, {1}=arg0, {2}=arg1, ...
112        // String methods
113        registry.add_method("String", "length", "{}.len");
114        registry.add_method_runtime("string", "length", "{}.len", "js_string");
115        registry.add_method_runtime(
116            "string",
117            "toUpperCase",
118            "(js_string.toUpper(js_allocator.g_alloc(), {}) catch \"\")",
119            "js_string",
120        );
121        registry.add_method_runtime(
122            "string",
123            "toLowerCase",
124            "(js_string.toLower(js_allocator.g_alloc(), {}) catch \"\")",
125            "js_string",
126        );
127        registry.add_method_runtime(
128            "string",
129            "charAt",
130            "(js_string.charAt(js_allocator.g_alloc(), {}, {}) catch \"\")",
131            "js_string",
132        );
133        registry.add_method_runtime("string", "charCodeAt", "{0}[@intCast({1})]", "js_string");
134        registry.add_method_runtime(
135            "string",
136            "concat",
137            "(js_string.concat(js_allocator.g_alloc(), {}, {}) catch \"\")",
138            "js_string",
139        );
140        registry.add_method_runtime(
141            "string",
142            "includes",
143            "js_string.includes({}, {})",
144            "js_string",
145        );
146        registry.add_method_runtime(
147            "string",
148            "indexOf",
149            "js_string.indexOf({}, {})",
150            "js_string",
151        );
152        registry.add_method_runtime(
153            "string",
154            "startsWith",
155            "js_string.startsWith({}, {})",
156            "js_string",
157        );
158        registry.add_method_runtime(
159            "string",
160            "endsWith",
161            "js_string.endsWith({}, {})",
162            "js_string",
163        );
164        registry.add_method_runtime(
165            "string",
166            "slice",
167            "js_string.slice({}, {}, {})",
168            "js_string",
169        );
170        registry.add_method_runtime(
171            "string",
172            "split",
173            "(js_string.split(js_allocator.g_alloc(), {}, {}) catch &[_][]const u8{})",
174            "js_string",
175        );
176        registry.add_method_runtime(
177            "string",
178            "replace",
179            "(js_string.replace(js_allocator.g_alloc(), {}, {}, {}) catch \"\")",
180            "js_string",
181        );
182        registry.add_method_runtime("string", "trim", "js_string.trim({})", "js_string");
183        registry.add_method_runtime(
184            "string",
185            "repeat",
186            "(js_string.repeat(js_allocator.g_alloc(), {}, {}) catch \"\")",
187            "js_string",
188        );
189
190        // Console
191        registry.add_method_runtime("console", "log", "js_console.log({})", "js_console");
192        registry.add_method_runtime("console", "error", "js_console.err({})", "js_console");
193        registry.add_method_runtime("console", "warn", "js_console.warn({})", "js_console");
194
195        // JSON
196        registry.add_method_runtime(
197            "JSON",
198            "stringify",
199            "js_json.stringifyI64(js_allocator.g_alloc(), {})",
200            "js_json",
201        );
202        registry.add_method_runtime(
203            "JSON",
204            "parse",
205            "js_json.parse(js_allocator.g_alloc(), {})",
206            "js_json",
207        );
208
209        // Array
210        registry.add_method_runtime("Array", "isArray", "js_array.isArray({})", "js_array");
211        registry.add_method_runtime("array", "length", "{}.len", "js_array");
212        registry.add_method_runtime(
213            "array",
214            "push",
215            "(js_array.push(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})",
216            "js_array",
217        );
218        registry.add_method_runtime("array", "pop", "js_array.pop({})", "js_array");
219        registry.add_method_runtime("array", "shift", "js_array.shift({})", "js_array");
220        registry.add_method_runtime(
221            "array",
222            "unshift",
223            "(js_array.unshift(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})",
224            "js_array",
225        );
226        registry.add_method_runtime(
227            "array",
228            "join",
229            "(js_array.join(js_allocator.g_alloc(), {}, {}) catch \"\")",
230            "js_array",
231        );
232        registry.add_method_runtime(
233            "array",
234            "map",
235            "(js_array.map(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})",
236            "js_array",
237        );
238        registry.add_method_runtime(
239            "array",
240            "filter",
241            "(js_array.filter(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})",
242            "js_array",
243        );
244        registry.add_method_runtime("array", "indexOf", "js_array.indexOf({}, {})", "js_array");
245        registry.add_method_runtime("array", "includes", "js_array.includes({}, {})", "js_array");
246        registry.add_method_runtime(
247            "array",
248            "reverse",
249            "(js_array.reverse(js_allocator.g_alloc(), {}) catch &[_]i64{})",
250            "js_array",
251        );
252        registry.add_method_runtime("array", "slice", "js_array.slice({}, {}, {})", "js_array");
253        registry.add_method_runtime(
254            "array",
255            "concat",
256            "(js_array.concat(js_allocator.g_alloc(), {}, {}) catch &[_]i64{})",
257            "js_array",
258        );
259        registry.add_method_runtime(
260            "array",
261            "sort",
262            "(js_array.sort(js_allocator.g_alloc(), {}) catch &[_]i64{})",
263            "js_array",
264        );
265
266        // ── Tier 3: Object ──
267        registry.add_method_runtime(
268            "Object",
269            "keys",
270            "js_object.keys(js_allocator.g_alloc(), {})",
271            "js_object",
272        );
273        registry.add_method_runtime(
274            "Object",
275            "values",
276            "js_object.values(js_allocator.g_alloc(), {})",
277            "js_object",
278        );
279        registry.add_method_runtime("Object", "assign", "js_object.assign({}, {})", "js_object");
280        registry.add_method_runtime(
281            "Object",
282            "entries",
283            "js_object.entries(js_allocator.g_alloc(), {})",
284            "js_object",
285        );
286
287        // ── Tier 3: Number ──
288        registry.add_method_runtime(
289            "Number",
290            "isNaN",
291            "js_number.isNaN(@as(f64, @floatFromInt({})))",
292            "js_number",
293        );
294        registry.add_method_runtime(
295            "Number",
296            "isFinite",
297            "js_number.isFinite(@as(f64, @floatFromInt({})))",
298            "js_number",
299        );
300        registry.add_method_runtime(
301            "Number",
302            "isInteger",
303            "js_number.isInteger(@as(f64, @floatFromInt({})))",
304            "js_number",
305        );
306        registry.add_method_runtime("Number", "parseInt", "js_number.parseInt({})", "js_number");
307        registry.add_method_runtime(
308            "Number",
309            "parseFloat",
310            "js_number.parseFloat({})",
311            "js_number",
312        );
313
314        // ── Tier 3: Boolean ──
315        registry.add_method_runtime(
316            "Boolean",
317            "toString",
318            "if ({}) \"true\" else \"false\"",
319            "js_number",
320        );
321
322        // ── Tier 3: Promise (minimal synchronous support) ──
323        // Promise.resolve(value) → js_runtime.Promise.resolve(value)
324        // Promise.reject(reason) → js_runtime.Promise.reject(reason)
325        // js_runtime exports Promise (via js_promise)
326        registry.add_method("Promise", "resolve", "js_runtime.Promise.resolve({})");
327        registry.add_method("Promise", "reject", "js_runtime.Promise.reject({})");
328
329        // ── Tier 3: Date ──
330        registry.add_method_runtime("Date", "now", "js_date.now()", "js_date");
331        registry.add_method_runtime("Date", "getTime", "js_date.getTime({})", "js_date");
332        registry.add_method_runtime("Date", "getFullYear", "js_date.getFullYear({})", "js_date");
333        registry.add_method_runtime("Date", "getMonth", "js_date.getMonth({})", "js_date");
334        registry.add_method_runtime("Date", "getDate", "js_date.getDate({})", "js_date");
335        registry.add_method_runtime("Date", "getDay", "js_date.getDay({})", "js_date");
336        registry.add_method_runtime("Date", "getHours", "js_date.getHours({})", "js_date");
337        registry.add_method_runtime("Date", "getMinutes", "js_date.getMinutes({})", "js_date");
338        registry.add_method_runtime("Date", "getSeconds", "js_date.getSeconds({})", "js_date");
339        registry.add_method_runtime(
340            "Date",
341            "parse",
342            "std.fmt.parseInt(i64, {}, 10) catch @as(i64, 0)",
343            "js_date",
344        );
345
346        // ── Tier 3: Map (instance methods) ──
347        registry.add_method_runtime("map", "get", "{0}.get({1})", "js_map");
348        registry.add_method_runtime(
349            "map",
350            "set",
351            "{0}.set({1}, {2}) catch unreachable",
352            "js_map",
353        );
354        registry.add_method_runtime("map", "has", "{0}.has({1})", "js_map");
355        registry.add_method_runtime("map", "delete", "{0}.delete({1})", "js_map");
356        registry.add_method_runtime("map", "clear", "{0}.clear()", "js_map");
357        registry.add_method_runtime("map", "size", "{0}.size()", "js_map");
358
359        // ── Tier 3: Set (instance methods) ──
360        registry.add_method_runtime("set", "add", "{0}.add({1}) catch unreachable", "js_set");
361        registry.add_method_runtime("set", "has", "{0}.has({1})", "js_set");
362        registry.add_method_runtime("set", "delete", "{0}.delete({1})", "js_set");
363        registry.add_method_runtime("set", "clear", "{0}.clear()", "js_set");
364        registry.add_method_runtime("set", "size", "{0}.size()", "js_set");
365
366        // ── Tier 3: RegExp ──
367        registry.add_method_runtime("RegExp", "test", "js_regexp.test_({}, {})", "js_regexp");
368        registry.add_method_runtime(
369            "RegExp",
370            "exec",
371            "js_regexp.exec(js_allocator.g_alloc(), {}, {})",
372            "js_regexp",
373        );
374
375        // ── Tier 3: TypedArray ──
376        // Int32Array
377        registry.add_method_runtime("Int32Array", "from", "(js_runtime.js_typedarray.fromI64AsI32(js_allocator.g_alloc(), {}) catch js_runtime.js_typedarray.emptyI32())", "js_typedarray");
378        registry.add_method_runtime("int32array", "length", "{}.len", "js_typedarray");
379        registry.add_method_runtime(
380            "int32array",
381            "get",
382            "js_runtime.js_typedarray.getI32({}, {})",
383            "js_typedarray",
384        );
385        registry.add_method_runtime(
386            "int32array",
387            "set",
388            "js_runtime.js_typedarray.setI32({}, {}, {})",
389            "js_typedarray",
390        );
391        registry.add_method_runtime(
392            "int32array",
393            "slice",
394            "js_runtime.js_typedarray.sliceI32({}, {}, {})",
395            "js_typedarray",
396        );
397        registry.add_method_runtime(
398            "int32array",
399            "subarray",
400            "js_runtime.js_typedarray.subarrayI32({}, {}, {})",
401            "js_typedarray",
402        );
403        registry.add_method_runtime(
404            "int32array",
405            "copyWithin",
406            "js_runtime.js_typedarray.copyWithinI32({}, {}, {}, {})",
407            "js_typedarray",
408        );
409        registry.add_method_runtime(
410            "int32array",
411            "fill",
412            "js_runtime.js_typedarray.fillI32({}, {}, {}, {})",
413            "js_typedarray",
414        );
415        registry.add_method_runtime(
416            "int32array",
417            "buffer",
418            "js_runtime.js_typedarray.bufferI32({})",
419            "js_typedarray",
420        );
421        registry.add_method_runtime(
422            "int32array",
423            "byteLength",
424            "js_runtime.js_typedarray.byteLengthI32({})",
425            "js_typedarray",
426        );
427        registry.add_method_runtime(
428            "int32array",
429            "byteOffset",
430            "js_runtime.js_typedarray.byteOffset()",
431            "js_typedarray",
432        );
433
434        // Uint8Array
435        registry.add_method_runtime("Uint8Array", "from", "(js_runtime.js_typedarray.fromI64AsU8(js_allocator.g_alloc(), {}) catch js_runtime.js_typedarray.emptyU8())", "js_typedarray");
436        registry.add_method_runtime("uint8array", "length", "{}.len", "js_typedarray");
437        registry.add_method_runtime(
438            "uint8array",
439            "get",
440            "js_runtime.js_typedarray.getU8({}, {})",
441            "js_typedarray",
442        );
443        registry.add_method_runtime(
444            "uint8array",
445            "set",
446            "js_runtime.js_typedarray.setU8({}, {}, {})",
447            "js_typedarray",
448        );
449        registry.add_method_runtime(
450            "uint8array",
451            "slice",
452            "js_runtime.js_typedarray.sliceU8({}, {}, {})",
453            "js_typedarray",
454        );
455        registry.add_method_runtime(
456            "uint8array",
457            "subarray",
458            "js_runtime.js_typedarray.subarrayU8({}, {}, {})",
459            "js_typedarray",
460        );
461        registry.add_method_runtime(
462            "uint8array",
463            "copyWithin",
464            "js_runtime.js_typedarray.copyWithinU8({}, {}, {}, {})",
465            "js_typedarray",
466        );
467        registry.add_method_runtime(
468            "uint8array",
469            "fill",
470            "js_runtime.js_typedarray.fillU8({}, {}, {}, {})",
471            "js_typedarray",
472        );
473        registry.add_method_runtime(
474            "uint8array",
475            "buffer",
476            "js_runtime.js_typedarray.bufferU8({})",
477            "js_typedarray",
478        );
479        registry.add_method_runtime(
480            "uint8array",
481            "byteLength",
482            "js_runtime.js_typedarray.byteLengthU8({})",
483            "js_typedarray",
484        );
485        registry.add_method_runtime(
486            "uint8array",
487            "byteOffset",
488            "js_runtime.js_typedarray.byteOffset()",
489            "js_typedarray",
490        );
491
492        // Float64Array
493        registry.add_method_runtime("Float64Array", "from", "(js_runtime.js_typedarray.fromI64AsF64(js_allocator.g_alloc(), {}) catch js_runtime.js_typedarray.emptyF64())", "js_typedarray");
494        registry.add_method_runtime("float64array", "length", "{}.len", "js_typedarray");
495        registry.add_method_runtime(
496            "float64array",
497            "get",
498            "js_runtime.js_typedarray.getF64({}, {})",
499            "js_typedarray",
500        );
501        registry.add_method_runtime(
502            "float64array",
503            "set",
504            "js_runtime.js_typedarray.setF64({}, {}, {})",
505            "js_typedarray",
506        );
507        registry.add_method_runtime(
508            "float64array",
509            "slice",
510            "js_runtime.js_typedarray.sliceF64({}, {}, {})",
511            "js_typedarray",
512        );
513        registry.add_method_runtime(
514            "float64array",
515            "subarray",
516            "js_runtime.js_typedarray.subarrayF64({}, {}, {})",
517            "js_typedarray",
518        );
519        registry.add_method_runtime(
520            "float64array",
521            "copyWithin",
522            "js_runtime.js_typedarray.copyWithinF64({}, {}, {}, {})",
523            "js_typedarray",
524        );
525        registry.add_method_runtime(
526            "float64array",
527            "fill",
528            "js_runtime.js_typedarray.fillF64({}, {}, {}, {})",
529            "js_typedarray",
530        );
531        registry.add_method_runtime(
532            "float64array",
533            "buffer",
534            "js_runtime.js_typedarray.bufferF64({})",
535            "js_typedarray",
536        );
537        registry.add_method_runtime(
538            "float64array",
539            "byteLength",
540            "js_runtime.js_typedarray.byteLengthF64({})",
541            "js_typedarray",
542        );
543        registry.add_method_runtime(
544            "float64array",
545            "byteOffset",
546            "js_runtime.js_typedarray.byteOffset()",
547            "js_typedarray",
548        );
549
550        // ── Tier 4: Rust via C ABI (reserved for custom host functions) ──
551
552        registry
553    }
554
555    /// Register host functions from a HostFnRegistry so they can be called
556    /// from JS code. These functions are defined in Rust with `#[no_mangle] pub extern "C"`.
557    ///
558    /// For functions with string params/returns, the template calls the `_wrap` variant
559    /// (generated in host.zig) which handles `[]const u8` ↔ `[*:0]const u8` conversion.
560    pub fn register_host_fns(&mut self, host_fns: &HostFnRegistry) {
561        for def in host_fns.sync_fns() {
562            // Build the template: host.fnName(arg1, arg2, ...)
563            let args: String = (0..def.params.len())
564                .map(|i| format!("{{{}}}", i))
565                .collect::<Vec<_>>()
566                .join(", ");
567
568            // Check if this function needs the string conversion wrapper
569            let has_string =
570                def.params.iter().any(|(_, t)| *t == ZigType::Str) || def.ret_type == ZigType::Str;
571            let fn_name = if has_string {
572                format!("{}_wrap", def.name)
573            } else {
574                def.name.clone()
575            };
576            let template = format!("host.{}({})", fn_name, args);
577
578            // Store return type
579            let return_type = def.ret_type.clone();
580
581            self.globals.insert(
582                def.name.clone(),
583                BuiltinTranslation::with_return_type(template, return_type),
584            );
585        }
586    }
587
588    fn add_method(&mut self, object: &str, method: &str, template: &str) {
589        let key = format!("{}.{}", object, method);
590        self.methods
591            .insert(key, BuiltinTranslation::new(template.to_string()));
592    }
593
594    fn add_method_runtime(&mut self, object: &str, method: &str, template: &str, _dep: &str) {
595        self.add_method(object, method, template);
596    }
597
598    fn add_global(&mut self, name: &str, template: &str) {
599        self.globals.insert(
600            name.to_string(),
601            BuiltinTranslation::new(template.to_string()),
602        );
603    }
604
605    fn add_property(&mut self, object: &str, property: &str, zig_expr: &str) {
606        let key = format!("{}.{}", object, property);
607        self.properties.insert(key, zig_expr.to_string());
608    }
609
610    /// Look up a method call: `object.method(...)` → Zig translation
611    pub fn lookup_method(&self, object: &str, method: &str) -> Option<&BuiltinTranslation> {
612        let key = format!("{}.{}", object, method);
613        self.methods.get(&key)
614    }
615
616    /// Look up a global function call: `func(...)` → Zig translation
617    pub fn lookup_global(&self, name: &str) -> Option<&BuiltinTranslation> {
618        self.globals.get(name)
619    }
620
621    /// Look up the return type of a global function (if known).
622    pub fn lookup_global_return_type(&self, name: &str) -> Option<&crate::native_proto::ZigType> {
623        self.globals
624            .get(name)
625            .and_then(|trans| trans.return_type.as_ref())
626    }
627
628    /// Look up a static property: `Obj.prop` → Zig expression
629    pub fn lookup_property(&self, object: &str, property: &str) -> Option<&str> {
630        let key = format!("{}.{}", object, property);
631        self.properties.get(&key).map(|s| s.as_str())
632    }
633}
634
635impl Default for BuiltinRegistry {
636    fn default() -> Self {
637        Self::new()
638    }
639}