1use crate::host::HostFnRegistry;
2use std::collections::HashMap;
3
4#[derive(Debug, Clone)]
6pub struct BuiltinTranslation {
7 pub template: String,
9}
10
11pub struct BuiltinRegistry {
13 methods: HashMap<String, BuiltinTranslation>,
15 globals: HashMap<String, BuiltinTranslation>,
17 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 registry.add_property("Math", "PI", "std.math.pi");
31 registry.add_property("Math", "E", "std.math.e");
32
33 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({}))"); 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 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 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 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 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 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 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 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 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 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 registry.add_method_runtime("Boolean", "toString", "if ({}) \"true\" else \"false\"", "js_number");
137
138 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 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 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 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 registry
170 }
171
172 pub fn register_host_fns(&mut self, host_fns: &HostFnRegistry) {
175 for def in host_fns.sync_fns() {
176 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 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 pub fn lookup_global(&self, name: &str) -> Option<&BuiltinTranslation> {
222 self.globals.get(name)
223 }
224
225 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}