1pub(crate) use alloc::format;
7pub(crate) use alloc::rc::Rc;
8pub(crate) use alloc::string::{String, ToString};
9pub(crate) use alloc::vec;
10pub(crate) use alloc::vec::Vec;
11pub(crate) use core::cell::RefCell;
12pub(crate) use core::sync::atomic::{AtomicU64, Ordering};
13
14use super::interp::{Interp, Scope};
15use super::value::*;
16
17const ARRAY_PROTO_METHODS: &[&str] = &[
21 "push", "pop", "shift", "unshift", "slice", "splice", "concat",
22 "join", "reverse", "sort", "indexOf", "lastIndexOf", "includes",
23 "find", "findIndex", "findLast", "findLastIndex", "filter", "map",
24 "forEach", "reduce", "reduceRight", "some", "every", "flat",
25 "flatMap", "fill", "copyWithin", "at", "keys", "values", "entries",
26 "toString", "toLocaleString", "toSorted", "toReversed", "toSpliced", "with",
27 "Symbol(Symbol.iterator)",
28];
29
30const STRING_PROTO_METHODS: &[&str] = &[
36 "charAt", "charCodeAt", "codePointAt", "localeCompare", "indexOf",
37 "lastIndexOf", "includes", "startsWith", "endsWith", "slice",
38 "substring", "substr", "toUpperCase", "toLowerCase", "trim",
39 "trimStart", "trimEnd", "split", "replace", "replaceAll", "match",
40 "matchAll", "search", "repeat", "concat", "padStart", "padEnd",
41 "at", "toString", "valueOf", "normalize", "toLocaleUpperCase",
42 "toLocaleLowerCase", "trimLeft", "trimRight", "isWellFormed", "toWellFormed",
43 "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize",
44 "italics", "link", "small", "strike", "sub", "sup",
45 "Symbol(Symbol.iterator)",
46];
47
48const ES_BUILTIN_GLOBALS: &[&str] = &[
51 "Object", "Function", "Array", "String", "Number", "Boolean", "Symbol", "BigInt", "Math", "JSON",
52 "Reflect", "Promise", "RegExp", "Date", "Map", "Set", "WeakMap", "WeakSet", "WeakRef",
53 "FinalizationRegistry", "Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError",
54 "EvalError", "URIError", "SuppressedError", "AggregateError", "ArrayBuffer", "SharedArrayBuffer", "Atomics",
55 "DisposableStack", "AsyncDisposableStack", "DataView", "Proxy", "Intl",
56 "Iterator", "Uint8Array", "Int8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array",
57 "Uint32Array", "Float16Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array",
58];
59
60pub(crate) fn ecma_noop(_: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
62 Ok(Value::Undefined)
63}
64
65pub(crate) fn nv(name: &str, f: NativeFn) -> Value {
67 Value::Object(Obj::native(name, f))
68}
69
70pub(crate) fn arg(args: &[Value], i: usize) -> Value {
72 args.get(i).cloned().unwrap_or(Value::Undefined)
73}
74
75pub(crate) fn obj_prop(v: &Value, key: &str) -> Option<Value> {
77 if let Value::Object(o) = v {
78 o.borrow().props.get(key).cloned()
79 } else {
80 None
81 }
82}
83
84pub(crate) fn prim_num_args<'a>(
87 it: &mut Interp,
88 a: &'a [Value],
89) -> Result<alloc::borrow::Cow<'a, [Value]>, Value> {
90 if !a.iter().any(|v| matches!(v, Value::Object(_))) {
91 return Ok(alloc::borrow::Cow::Borrowed(a));
92 }
93 let mut out = Vec::with_capacity(a.len());
94 for v in a {
95 out.push(if matches!(v, Value::Object(_)) {
96 it.to_primitive(v.clone(), "number")?
97 } else {
98 v.clone()
99 });
100 }
101 Ok(alloc::borrow::Cow::Owned(out))
102}
103
104pub fn populate_builtin_protos(global: &Rc<RefCell<Scope>>) {
109 type Lookup = fn(&str) -> Option<(&'static str, NativeFn)>;
110 const DATE_KEYS: &[&str] = &[
111 "getTime", "valueOf", "getFullYear", "getUTCFullYear", "getMonth", "getUTCMonth", "getDate", "getUTCDate",
112 "getHours", "getUTCHours", "getMinutes", "getUTCMinutes", "getSeconds", "getUTCSeconds", "getMilliseconds",
113 "getUTCMilliseconds", "getDay", "getUTCDay", "getYear", "setYear", "setTime", "setFullYear", "setUTCFullYear",
114 "setMonth", "setUTCMonth", "setDate", "setUTCDate", "setHours", "setUTCHours", "setMinutes", "setUTCMinutes",
115 "setSeconds", "setUTCSeconds", "setMilliseconds", "setUTCMilliseconds", "toISOString", "toJSON", "toString",
116 "toLocaleString", "toDateString", "toUTCString", "toGMTString", "toLocaleDateString", "toTimeString",
117 "toLocaleTimeString", "getTimezoneOffset", "Symbol(Symbol.toPrimitive)",
118 ];
119 const COLL_KEYS: &[&str] = &[
120 "set", "get", "getOrInsert", "getOrInsertComputed", "has", "add", "delete", "clear", "forEach", "keys", "values", "entries", "Symbol(Symbol.iterator)",
121 "union", "intersection", "difference", "symmetricDifference", "isSubsetOf", "isSupersetOf", "isDisjointFrom",
122 ];
123 const NUM_KEYS: &[&str] = &["toFixed", "toString", "toExponential", "toPrecision", "valueOf", "toLocaleString"];
124 let map_fn: Lookup = |k| mapset_method_fn(true, k);
125 let set_fn: Lookup = |k| mapset_method_fn(false, k);
126 let table: [(&str, &[&str], Lookup); 7] = [
127 ("Number", NUM_KEYS, props_methods::number_builtin_fn),
128 ("Boolean", NUM_KEYS, props_methods::boolean_builtin_fn),
129 ("BigInt", NUM_KEYS, props_methods::bigint_builtin_fn),
130 ("Promise", &["then", "catch", "finally"], promise_method_fn),
131 ("Date", DATE_KEYS, date_method_fn),
132 ("Map", COLL_KEYS, map_fn),
133 ("Set", COLL_KEYS, set_fn),
134 ];
135 let g = global.borrow();
136 for (ctor_name, keys, lookup) in table {
137 let Some(Value::Object(c)) = g.vars.get(ctor_name) else { continue };
138 let existing = match c.borrow().props.get("prototype") {
139 Some(Value::Object(p)) => Some(p.clone()),
140 _ => None,
141 };
142 let proto = match existing {
143 Some(p) => p,
144 None => {
145 let p = Obj::plain();
146 p.borrow_mut().props.insert("constructor".into(), Value::Object(c.clone()));
147 c.borrow_mut().props.insert("prototype".into(), Value::Object(p.clone()));
148 p
149 }
150 };
151 let mut pb = proto.borrow_mut();
152 for k in keys {
153 if pb.props.contains_key(k) || pb.has_accessor(k) {
154 continue;
155 }
156 if let Some((name, f)) = lookup(k) {
157 let fn_name = if ctor_name == "Date" {
158 if *k == "toGMTString" {
159 "toUTCString"
160 } else if *k == "Symbol(Symbol.toPrimitive)" {
161 name
162 } else {
163 *k
164 }
165 } else {
166 name
167 };
168 pb.props.insert(String::from(*k).into(), Value::Object(Obj::native(fn_name, f)));
169 if *k == "Symbol(Symbol.toPrimitive)" {
170 pb.insert_attr(
171 *k,
172 PropertyAttributes { writable: false, enumerable: false, configurable: true },
173 );
174 }
175 }
176 }
177 if ctor_name == "Number" {
180 pb.rare_data_mut().primitive = Some(Value::Number(0.0));
181 } else if ctor_name == "Boolean" {
182 pb.rare_data_mut().primitive = Some(Value::Bool(false));
183 }
184 if ctor_name == "Date" {
186 if let Some(utc) = pb.props.get("toUTCString").cloned() {
187 pb.props.insert("toGMTString".into(), utc);
188 }
189 } else if ctor_name == "Set" {
190 if let Some(vals) = pb.props.get("values").cloned() {
191 pb.props.insert("keys".into(), vals.clone());
192 pb.props.insert("Symbol(Symbol.iterator)".into(), vals);
193 }
194 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
195 pb.insert_accessor("size", Accessor { get: Some(nv("get size", set_get_size)), set: None });
196 pb.insert_attr("size", acc_attr);
197 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Set"));
198 pb.insert_attr("Symbol(Symbol.toStringTag)", acc_attr);
199 } else if ctor_name == "Map" {
200 if let Some(ents) = pb.props.get("entries").cloned() {
201 pb.props.insert("Symbol(Symbol.iterator)".into(), ents);
202 }
203 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
204 pb.insert_accessor("size", Accessor { get: Some(nv("get size", map_get_size)), set: None });
205 pb.insert_attr("size", acc_attr);
206 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Map"));
207 pb.insert_attr("Symbol(Symbol.toStringTag)", acc_attr);
208 } else if ctor_name == "BigInt" {
209 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
210 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("BigInt"));
211 pb.insert_attr("Symbol(Symbol.toStringTag)", acc_attr);
212 }
213 }
214
215 let install_proto_methods = |ctor_name: &str, methods: &[(&str, NativeFn)]| {
217 let Some(Value::Object(c)) = g.vars.get(ctor_name) else { return };
218 let Some(Value::Object(p)) = c.borrow().props.get("prototype").cloned() else { return };
219 let mut pb = p.borrow_mut();
220 for (k, f) in methods {
221 if !pb.props.contains_key(k) && !pb.has_accessor(k) {
222 pb.props.insert(String::from(*k).into(), Value::Object(Obj::native(k, *f)));
223 }
224 }
225 };
226 install_proto_methods(
227 "DataView",
228 &[
229 ("getInt8", dv_get_int8),
230 ("getUint8", dv_get_uint8),
231 ("getInt16", dv_get_int16),
232 ("getUint16", dv_get_uint16),
233 ("getInt32", dv_get_int32),
234 ("getUint32", dv_get_uint32),
235 ("getFloat16", dv_get_float16),
236 ("getFloat32", dv_get_float32),
237 ("getFloat64", dv_get_float64),
238 ("getBigInt64", dv_get_big_int64),
239 ("getBigUint64", dv_get_big_uint64),
240 ("setInt8", dv_set_int8),
241 ("setUint8", dv_set_uint8),
242 ("setInt16", dv_set_int16),
243 ("setUint16", dv_set_uint16),
244 ("setInt32", dv_set_int32),
245 ("setUint32", dv_set_uint32),
246 ("setFloat16", dv_set_float16),
247 ("setFloat32", dv_set_float32),
248 ("setFloat64", dv_set_float64),
249 ("setBigInt64", dv_set_big_int64),
250 ("setBigUint64", dv_set_big_uint64),
251 ],
252 );
253 install_proto_methods(
254 "ArrayBuffer",
255 &[
256 ("slice", arraybuffer_slice),
257 ("sliceToImmutable", arraybuffer_slice_to_immutable),
258 ("resize", arraybuffer_resize),
259 ("transfer", arraybuffer_transfer),
260 ("transferToFixedLength", arraybuffer_transfer_fixed),
261 ("transferToImmutable", arraybuffer_transfer_to_immutable),
262 ],
263 );
264 let u8_to_base64: NativeFn = |it, this, a| {
265 if !matches!(&this, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) && matches!(o.borrow().props.get("_ta_kind"), Some(Value::Str(s)) if s.as_str() == "Uint8Array")) {
266 return Err(it.type_error("Method Uint8Array.prototype.toBase64 called on incompatible receiver"));
267 }
268 ta_to_base64(it, this, a)
269 };
270 let u8_to_hex: NativeFn = |it, this, a| {
271 if !matches!(&this, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) && matches!(o.borrow().props.get("_ta_kind"), Some(Value::Str(s)) if s.as_str() == "Uint8Array")) {
272 return Err(it.type_error("Method Uint8Array.prototype.toHex called on incompatible receiver"));
273 }
274 ta_to_hex(it, this, a)
275 };
276 let u8_set_from_base64: NativeFn = |it, this, a| {
277 if !matches!(&this, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) && matches!(o.borrow().props.get("_ta_kind"), Some(Value::Str(s)) if s.as_str() == "Uint8Array")) {
278 return Err(it.type_error("Method Uint8Array.prototype.setFromBase64 called on incompatible receiver"));
279 }
280 ta_set_from_base64(it, this, a)
281 };
282 let u8_set_from_hex: NativeFn = |it, this, a| {
283 if !matches!(&this, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) && matches!(o.borrow().props.get("_ta_kind"), Some(Value::Str(s)) if s.as_str() == "Uint8Array")) {
284 return Err(it.type_error("Method Uint8Array.prototype.setFromHex called on incompatible receiver"));
285 }
286 ta_set_from_hex(it, this, a)
287 };
288 let _ = u8_set_from_hex;
289 install_proto_methods(
290 "Uint8Array",
291 &[
292 ("toBase64", u8_to_base64),
293 ("toHex", u8_to_hex),
294 ("setFromBase64", u8_set_from_base64),
295 ("setFromHex", u8_set_from_hex),
296 ],
297 );
298 install_proto_methods(
299 "WeakMap",
300 &[
301 ("get", wm_get),
302 ("set", wm_set),
303 ("has", wm_has),
304 ("delete", wm_delete),
305 ("getOrInsert", wm_get_or_insert),
306 ("getOrInsertComputed", wm_get_or_insert_computed),
307 ],
308 );
309 install_proto_methods(
310 "WeakSet",
311 &[("add", ws_add), ("has", ws_has), ("delete", ws_delete)],
312 );
313 for (cname, tag) in [("WeakMap", "WeakMap"), ("WeakSet", "WeakSet")] {
314 if let Some(Value::Object(c)) = g.vars.get(cname) {
315 if let Some(Value::Object(p)) = c.borrow().props.get("prototype").cloned() {
316 let mut pb = p.borrow_mut();
317 if !pb.props.contains_key("Symbol(Symbol.toStringTag)") {
318 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str(tag));
319 pb.insert_attr(
320 "Symbol(Symbol.toStringTag)",
321 PropertyAttributes { writable: false, enumerable: false, configurable: true },
322 );
323 }
324 }
325 }
326 }
327 install_proto_methods("WeakRef", &[("deref", wr_deref)]);
328 install_proto_methods(
329 "FinalizationRegistry",
330 &[("register", fr_register), ("unregister", fr_unregister), ("cleanupSome", ecma_noop)],
331 );
332 install_proto_methods(
333 "Iterator",
334 &[
335 ("next", iterator_next),
336 ("map", iterator_map),
337 ("filter", iterator_filter),
338 ("take", iterator_take),
339 ("drop", iterator_drop),
340 ("toArray", iterator_to_array),
341 ("forEach", iterator_for_each),
342 ("reduce", iterator_reduce),
343 ("some", iterator_some),
344 ("every", iterator_every),
345 ("find", iterator_find),
346 ("flatMap", iterator_flat_map),
347 ("chunks", iterator_chunks),
348 ("windows", iterator_windows),
349 ("includes", iterator_includes),
350 ("join", iterator_join),
351 ],
352 );
353 drop(g);
354 install_iterator_extras(global);
355 install_generator_protos(global);
356 if let Some(Value::Object(pc)) = global.borrow().vars.get("Promise") {
357 if let Some(Value::Object(pp)) = pc.borrow().props.get("prototype").cloned() {
358 let mut ppb = pp.borrow_mut();
359 if !ppb.props.contains_key("Symbol(Symbol.toStringTag)") {
360 ppb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Promise"));
361 ppb.insert_attr(
362 "Symbol(Symbol.toStringTag)",
363 PropertyAttributes { writable: false, configurable: true, enumerable: false },
364 );
365 }
366 }
367 }
368}
369
370pub fn mark_builtin_props(global: &Rc<RefCell<Scope>>) {
375 let hidden = PropertyAttributes { writable: true, configurable: true, enumerable: false };
376 let constant = PropertyAttributes { writable: false, configurable: false, enumerable: false };
377 let g = global.borrow();
378 for name in ["Math", "JSON", "Reflect", "Atomics"] {
380 if let Some(Value::Object(o)) = g.vars.get(name) {
381 let mut b = o.borrow_mut();
382 if !b.props.contains_key("Symbol(Symbol.toStringTag)") {
383 b.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str(name));
384 b.insert_attr(
385 "Symbol(Symbol.toStringTag)",
386 PropertyAttributes { writable: false, configurable: true, enumerable: false },
387 );
388 }
389 }
390 }
391 for name in ES_BUILTIN_GLOBALS {
392 let Some(Value::Object(c)) = g.vars.get(name) else { continue };
393 let proto = match c.borrow().props.get("prototype") {
394 Some(Value::Object(p)) => Some(p.clone()),
395 _ => None,
396 };
397 {
398 let mut b = c.borrow_mut();
399 let keys: Vec<(String, bool)> = b
400 .props
401 .iter()
402 .map(|(k, v)| (k.to_string(), k.as_str() == "prototype" || !matches!(v, Value::Object(_))))
403 .collect();
404 for (k, is_const) in keys {
405 if b.get_attr(&k).is_none() {
406 b.insert_attr(k, if is_const { constant } else { hidden });
407 }
408 }
409 }
410 if let Some(p) = proto {
411 let mut b = p.borrow_mut();
412 let keys: Vec<String> = b.props.keys().map(|k| k.to_string()).collect();
413 for k in keys {
414 if b.get_attr(&k).is_none() {
415 b.insert_attr(k, hidden);
416 }
417 }
418 }
419 }
420}
421
422pub fn ensure_ctor_prototypes(global: &Rc<RefCell<Scope>>) {
424 let g = global.borrow();
425 let ctors: Vec<(String, Rc<RefCell<Obj>>)> = g
426 .vars
427 .iter()
428 .filter(|(k, _)| k.chars().next().is_some_and(|c| c.is_ascii_uppercase()) && k.as_ref() != "Proxy")
429 .filter_map(|(k, v)| match v {
430 Value::Object(o) if o.borrow().is_callable() && !o.borrow().props.contains_key("prototype") => {
431 Some((k.to_string(), o.clone()))
432 }
433 _ => None,
434 })
435 .collect();
436 drop(g);
437 for (_name, ctor) in ctors {
438 let proto = Obj::plain();
439 proto.borrow_mut().props.insert("constructor".into(), Value::Object(ctor.clone()));
440 ctor.borrow_mut().props.insert("prototype".into(), Value::Object(proto));
441 }
442}
443
444pub fn install(global: &Rc<RefCell<Scope>>) {
446 {
447 let mut g = global.borrow_mut();
448
449 let console = Obj::plain();
451 {
452 let mut c = console.borrow_mut();
453 c.props.insert("log".into(), nv("console.log", console_log));
454 c.props.insert("error".into(), nv("console.error", console_log));
455 c.props.insert("warn".into(), nv("console.warn", console_log));
456 c.props.insert("info".into(), nv("console.info", console_log));
457 c.props.insert("debug".into(), nv("console.debug", console_log));
458 c.props.insert("trace".into(), nv("console.trace", console_log));
459 c.props.insert("dir".into(), nv("console.dir", console_log));
460 c.props.insert("table".into(), nv("console.table", console_log));
461 c.props.insert("group".into(), nv("console.group", console_log));
462 c.props.insert("groupEnd".into(), nv("console.groupEnd", ecma_noop));
463 c.props.insert("groupCollapsed".into(), nv("console.groupCollapsed", console_log));
464 c.props.insert("count".into(), nv("console.count", ecma_noop));
465 c.props.insert("assert".into(), nv("console.assert", console_log));
466 c.props.insert("time".into(), nv("console.time", ecma_noop));
467 c.props.insert("timeEnd".into(), nv("console.timeEnd", ecma_noop));
468 }
469 g.vars.insert("console".into(), Value::Object(console));
470
471 let math = Obj::plain();
473 {
474 let mut m = math.borrow_mut();
475 m.props.insert("PI".into(), Value::Number(core::f64::consts::PI));
476 m.props.insert("E".into(), Value::Number(core::f64::consts::E));
477 m.props.insert("floor".into(), nv("Math.floor", math_floor));
478 m.props.insert("ceil".into(), nv("Math.ceil", math_ceil));
479 m.props.insert("round".into(), nv("Math.round", math_round));
480 m.props.insert("trunc".into(), nv("Math.trunc", math_trunc));
481 m.props.insert("abs".into(), nv("Math.abs", math_abs));
482 m.props.insert("sign".into(), nv("Math.sign", math_sign));
483 m.props.insert("sqrt".into(), nv("Math.sqrt", math_sqrt));
484 m.props.insert("pow".into(), nv("Math.pow", math_pow));
485 m.props.insert("min".into(), nv("Math.min", math_min));
486 m.props.insert("max".into(), nv("Math.max", math_max));
487 m.props.insert("random".into(), nv("Math.random", math_random));
488 m.props.insert("sin".into(), nv("Math.sin", math_sin));
489 m.props.insert("cos".into(), nv("Math.cos", math_cos));
490 m.props.insert("tan".into(), nv("Math.tan", math_tan));
491 m.props.insert("asin".into(), nv("Math.asin", math_asin));
492 m.props.insert("acos".into(), nv("Math.acos", math_acos));
493 m.props.insert("atan".into(), nv("Math.atan", math_atan));
494 m.props.insert("atan2".into(), nv("Math.atan2", math_atan2));
495 m.props.insert("log".into(), nv("Math.log", math_log));
496 m.props.insert("log2".into(), nv("Math.log2", math_log2));
497 m.props.insert("log10".into(), nv("Math.log10", math_log10));
498 m.props.insert("cbrt".into(), nv("Math.cbrt", math_cbrt));
499 m.props.insert("hypot".into(), nv("Math.hypot", math_hypot));
500 m.props.insert("exp".into(), nv("Math.exp", math_exp));
501 m.props.insert("fround".into(), nv("Math.fround", math_fround));
502 m.props.insert("f16round".into(), nv("Math.f16round", math_f16round));
503 m.props.insert("clamp".into(), nv("Math.clamp", math_clamp));
504 m.props.insert("sumPrecise".into(), nv("Math.sumPrecise", math_sum_precise));
505 m.props.insert("clz32".into(), nv("Math.clz32", math_clz32));
506 m.props.insert("imul".into(), nv("Math.imul", math_imul));
507 m.props.insert("sinh".into(), nv("Math.sinh", math_sinh));
508 m.props.insert("cosh".into(), nv("Math.cosh", math_cosh));
509 m.props.insert("tanh".into(), nv("Math.tanh", math_tanh));
510 m.props.insert("asinh".into(), nv("Math.asinh", math_asinh));
511 m.props.insert("acosh".into(), nv("Math.acosh", math_acosh));
512 m.props.insert("atanh".into(), nv("Math.atanh", math_atanh));
513 m.props.insert("expm1".into(), nv("Math.expm1", math_expm1));
514 m.props.insert("log1p".into(), nv("Math.log1p", math_log1p));
515 m.props.insert("LN2".into(), Value::Number(core::f64::consts::LN_2));
516 m.props.insert("LN10".into(), Value::Number(core::f64::consts::LN_10));
517 m.props.insert("LOG2E".into(), Value::Number(core::f64::consts::LOG2_E));
518 m.props.insert("LOG10E".into(), Value::Number(core::f64::consts::LOG10_E));
519 m.props.insert("SQRT2".into(), Value::Number(core::f64::consts::SQRT_2));
520 m.props.insert("SQRT1_2".into(), Value::Number(core::f64::consts::FRAC_1_SQRT_2));
521 }
522 g.vars.insert("Math".into(), Value::Object(math));
523
524 g.vars.insert("Intl".into(), create_intl_object());
526
527 let json = Obj::plain();
529 {
530 let mut j = json.borrow_mut();
531 j.props.insert("parse".into(), nv("JSON.parse", json_parse));
532 j.props.insert("stringify".into(), nv("JSON.stringify", json_stringify));
533 j.props.insert("rawJSON".into(), nv("JSON.rawJSON", json_raw_json));
534 j.props.insert("isRawJSON".into(), nv("JSON.isRawJSON", json_is_raw_json));
535 }
536 g.vars.insert("JSON".into(), Value::Object(json));
537
538 let object_ctor = Obj::native("Object", object_ctor);
540 {
541 let mut b = object_ctor.borrow_mut();
542 b.props.insert("keys".into(), nv("Object.keys", object_keys));
543 b.props.insert("values".into(), nv("Object.values", object_values));
544 b.props.insert("entries".into(), nv("Object.entries", object_entries));
545 b.props.insert("assign".into(), nv("Object.assign", object_assign));
546 b.props.insert("fromEntries".into(), nv("Object.fromEntries", object_from_entries));
547 b.props.insert("getOwnPropertyNames".into(), nv("getOwnPropertyNames", object_get_own_property_names));
548 b.props.insert(
549 "getOwnPropertySymbols".into(),
550 nv("Object.getOwnPropertySymbols", |it: &mut Interp, _t: Value, a: &[Value]| {
551 let v = arg(a, 0);
552 if matches!(v, Value::Undefined | Value::Null) {
553 return Err(it.type_error("Cannot convert undefined or null to object"));
554 }
555 let mut syms: Vec<Value> = Vec::new();
556 if let Value::Object(o) = v {
557 if let Some(list) = proxy_own_keys_trap(it, &o)? {
558 let syms: Vec<Value> = list
559 .into_iter()
560 .filter(|k| matches!(k, Value::Str(s) if is_symbol_like_key(s)))
561 .collect();
562 return Ok(Value::Object(Obj::array(syms)));
563 }
564 let o = unwrap_proxy_target(&o);
565 let b = o.borrow();
566 for k in b.props.keys() {
567 if is_symbol_like_key(k) {
568 syms.push(Value::str(&**k));
569 }
570 }
571 if let Some(acc) = b.accessors() {
572 for k in acc.keys() {
573 if is_symbol_like_key(k) && !b.props.contains_key(k) {
574 syms.push(Value::str(&**k));
575 }
576 }
577 }
578 }
579 Ok(Value::Object(Obj::array(syms)))
580 }),
581 );
582 b.props.insert("freeze".into(), nv("Object.freeze", object_freeze));
583 b.props.insert("isFrozen".into(), nv("Object.isFrozen", object_is_frozen));
584 b.props.insert("seal".into(), nv("Object.seal", object_seal));
585 b.props.insert("isSealed".into(), nv("Object.isSealed", object_is_sealed));
586 b.props.insert("preventExtensions".into(), nv("Object.preventExtensions", object_prevent_extensions));
587 b.props.insert("isExtensible".into(), nv("Object.isExtensible", object_is_extensible));
588 b.props.insert("is".into(), nv("Object.is", object_is));
589 b.props.insert("create".into(), nv("Object.create", object_create));
590 b.props.insert("defineProperty".into(), nv("Object.defineProperty", object_define_property));
591 b.props.insert("defineProperties".into(), nv("Object.defineProperties", object_define_properties));
592 b.props.insert("getOwnPropertyDescriptor".into(), nv("Object.getOwnPropertyDescriptor", object_get_own_property_descriptor));
593 b.props.insert("getOwnPropertyDescriptors".into(), nv("Object.getOwnPropertyDescriptors", object_get_own_property_descriptors));
594 b.props.insert("hasOwn".into(), nv("Object.hasOwn", object_has_own_static));
595 b.props.insert("groupBy".into(), nv("Object.groupBy", object_group_by));
596 b.props.insert("getPrototypeOf".into(), nv("Object.getPrototypeOf", object_get_prototype_of));
597 b.props.insert("setPrototypeOf".into(), nv("Object.setPrototypeOf", object_set_prototype_of));
598 }
599 let object_proto = Obj::plain();
600 {
601 let mut op = object_proto.borrow_mut();
602 op.props.insert("constructor".into(), Value::Object(object_ctor.clone()));
603 for key in [
604 "toString",
605 "toLocaleString",
606 "valueOf",
607 "hasOwnProperty",
608 "isPrototypeOf",
609 "propertyIsEnumerable",
610 "__defineGetter__",
611 "__defineSetter__",
612 "__lookupGetter__",
613 "__lookupSetter__",
614 ] {
615 if let Some((name, f)) = props_methods::object_builtin_fn(key) {
616 op.props.insert(String::from(key).into(), nv(name, f));
617 }
618 }
619 op.insert_accessor(
620 "__proto__",
621 Accessor {
622 get: Some(nv("get __proto__", props_methods::obj_proto_get)),
623 set: Some(nv("set __proto__", props_methods::obj_proto_set)),
624 },
625 );
626 op.insert_attr(
627 "__proto__",
628 PropertyAttributes { writable: false, enumerable: false, configurable: true },
629 );
630 }
631 object_ctor.borrow_mut().props.insert("prototype".into(), Value::Object(object_proto.clone()));
632 g.vars.insert("Object".into(), Value::Object(object_ctor));
633
634 let array_ctor = Obj::native("Array", array_ctor);
636 let array_proto = Obj::array(Vec::new());
637 array_proto.borrow_mut().proto = Some(object_proto.clone());
638 let unscopables_obj = Obj::plain();
639 {
640 let mut u = unscopables_obj.borrow_mut();
641 u.set_null_proto(true);
642 for key in [
643 "at", "copyWithin", "entries", "fill", "find", "findIndex",
644 "findLast", "findLastIndex", "flat", "flatMap", "includes",
645 "keys", "toReversed", "toSorted", "toSpliced", "values",
646 ] {
647 u.props.insert(key.into(), Value::Bool(true));
648 }
649 }
650 {
651 let mut ap = array_proto.borrow_mut();
652 ap.props.insert("Symbol(Symbol.unscopables)".into(), Value::Object(unscopables_obj));
653 ap.insert_attr(
654 "Symbol(Symbol.unscopables)",
655 PropertyAttributes { writable: false, enumerable: false, configurable: true },
656 );
657 }
658 {
659 let probe = Obj::array(Vec::new());
660 let mut ap = array_proto.borrow_mut();
661 for key in ARRAY_PROTO_METHODS {
662 let v = props_methods::object_get(&probe, key);
663 if !matches!(v, Value::Undefined) {
664 ap.props.insert(String::from(*key).into(), v);
665 }
666 }
667 if let Some(vals) = ap.props.get("values").cloned() {
668 ap.props.insert("Symbol(Symbol.iterator)".into(), vals);
669 }
670 }
671 {
672 array_proto.borrow_mut().props.insert("constructor".into(), Value::Object(array_ctor.clone()));
673 array_proto.borrow_mut().hide_props(&["constructor"]);
674 let mut ac = array_ctor.borrow_mut();
675 ac.props.insert("prototype".into(), Value::Object(array_proto));
676 ac.props.insert("isArray".into(), nv("Array.isArray", array_is_array));
677 ac.props.insert("from".into(), nv("Array.from", array_from));
678 ac.props.insert("of".into(), nv("Array.of", array_of));
679 ac.props.insert("fromAsync".into(), nv("Array.fromAsync", array_from_async));
680 }
681 g.vars.insert("Array".into(), Value::Object(array_ctor));
682 g.vars.insert("\0import".into(), nv("import", promise::dynamic_import));
684
685 let string_ctor_v = nv("String", string_ctor);
687 if let Value::Object(sc) = &string_ctor_v {
688 let mut b = sc.borrow_mut();
689 b.props.insert("fromCharCode".into(), nv("String.fromCharCode", string_from_char_code));
690 b.props.insert("fromCodePoint".into(), nv("String.fromCodePoint", string_from_code_point));
691 b.props.insert("raw".into(), nv("String.raw", string_raw));
692 let string_proto = Obj::plain();
693 {
694 let mut sp = string_proto.borrow_mut();
695 sp.rare_data_mut().primitive = Some(Value::str(""));
696 for key in STRING_PROTO_METHODS {
697 let v = props_methods::string_get("", key);
698 if !matches!(v, Value::Undefined) {
699 sp.props.insert(String::from(*key).into(), v);
700 }
701 }
702 if let Some(ts) = sp.props.get("trimStart").cloned() {
703 sp.props.insert("trimLeft".into(), ts);
704 }
705 if let Some(te) = sp.props.get("trimEnd").cloned() {
706 sp.props.insert("trimRight".into(), te);
707 }
708 sp.props.insert("constructor".into(), string_ctor_v.clone());
709 sp.hide_props(&["constructor"]);
710 }
711 b.props.insert("prototype".into(), Value::Object(string_proto));
712 }
713 g.vars.insert("String".into(), string_ctor_v);
714
715 let parse_float_v = nv("parseFloat", global_parse_float);
717 let parse_int_v = nv("parseInt", global_parse_int);
718 let number_ctor_v = nv("Number", number_ctor);
719 if let Value::Object(nc) = &number_ctor_v {
720 let mut b = nc.borrow_mut();
721 b.props.insert("isInteger".into(), nv("Number.isInteger", number_is_integer));
722 b.props.insert("isSafeInteger".into(), nv("Number.isSafeInteger", number_is_safe_integer));
723 b.props.insert("isFinite".into(), nv("Number.isFinite", number_is_finite_static));
724 b.props.insert("isNaN".into(), nv("Number.isNaN", number_is_nan_static));
725 b.props.insert("parseFloat".into(), parse_float_v.clone());
726 b.props.insert("parseInt".into(), parse_int_v.clone());
727 b.props.insert("MAX_SAFE_INTEGER".into(), Value::Number(9007199254740991.0));
728 b.props.insert("MIN_SAFE_INTEGER".into(), Value::Number(-9007199254740991.0));
729 b.props.insert("EPSILON".into(), Value::Number(f64::EPSILON));
730 b.props.insert("MAX_VALUE".into(), Value::Number(f64::MAX));
731 b.props.insert("MIN_VALUE".into(), Value::Number(f64::from_bits(1)));
732 b.props.insert("NaN".into(), Value::Number(f64::NAN));
733 b.props.insert("POSITIVE_INFINITY".into(), Value::Number(f64::INFINITY));
734 b.props.insert("NEGATIVE_INFINITY".into(), Value::Number(f64::NEG_INFINITY));
735 }
736 g.vars.insert("Number".into(), number_ctor_v);
737 g.vars.insert("Boolean".into(), nv("Boolean", boolean_ctor));
738
739 let bigint_ctor_v = nv("BigInt", bigint_ctor);
740 if let Value::Object(bc) = &bigint_ctor_v {
741 let mut b = bc.borrow_mut();
742 b.props.insert("asIntN".into(), nv("BigInt.asIntN", bigint_as_int_n));
743 b.props.insert("asUintN".into(), nv("BigInt.asUintN", bigint_as_uint_n));
744 }
745 g.vars.insert("BigInt".into(), bigint_ctor_v);
746
747 g.vars.insert("parseInt".into(), parse_int_v);
749 g.vars.insert("parseFloat".into(), parse_float_v);
750 g.vars.insert("isNaN".into(), nv("isNaN", global_is_nan));
751 g.vars.insert("isFinite".into(), nv("isFinite", global_is_finite));
752 g.vars.insert("eval".into(), nv("eval", global_eval));
753 g.vars.insert("encodeURIComponent".into(), nv("encodeURIComponent", js_encode_uri_component));
754 g.vars.insert("decodeURIComponent".into(), nv("decodeURIComponent", js_decode_uri_component));
755 g.vars.insert("encodeURI".into(), nv("encodeURI", js_encode_uri));
756 g.vars.insert("decodeURI".into(), nv("decodeURI", js_decode_uri));
757 g.vars.insert("escape".into(), nv("escape", js_escape));
758 g.vars.insert("unescape".into(), nv("unescape", js_unescape));
759
760 let function_ctor_v = nv("Function", function_ctor);
762 if let Value::Object(fc) = &function_ctor_v {
763 let function_proto = Obj::native("", ecma_noop);
765 {
766 let mut fp = function_proto.borrow_mut();
767 fp.proto = Some(object_proto.clone());
768 fp.props.insert("constructor".into(), Value::Object(fc.clone()));
769 for key in ["call", "apply", "bind"] {
770 let v = props_methods::function_method(key);
771 if !matches!(v, Value::Undefined) {
772 fp.props.insert(String::from(key).into(), v);
773 }
774 }
775 fp.props.insert("toString".into(), nv("toString", props_methods::fn_to_string));
776 let has_inst = nv("[Symbol.hasInstance]", |it: &mut Interp, t: Value, a: &[Value]| {
777 if !matches!(&t, Value::Object(c) if c.borrow().is_callable()) {
779 return Ok(Value::Bool(false));
780 }
781 let o = arg(a, 0);
782 let Value::Object(obj) = &o else {
783 return Ok(Value::Bool(false));
784 };
785 let proto_val = it.get_property(&t, "prototype")?;
786 let Value::Object(target_proto) = proto_val else {
787 return Err(it.type_error("Function has non-object prototype in instanceof check"));
788 };
789 let mut cur = implicit_proto(it, obj);
790 let mut guard = 0u32;
791 while let Some(p) = cur {
792 if Rc::ptr_eq(&p, &target_proto) {
793 return Ok(Value::Bool(true));
794 }
795 cur = implicit_proto(it, &p);
796 guard += 1;
797 if guard > 1000 {
798 break;
799 }
800 }
801 Ok(Value::Bool(false))
802 });
803 fp.props.insert("Symbol(Symbol.hasInstance)".into(), has_inst);
804 fp.insert_attr(
805 "Symbol(Symbol.hasInstance)",
806 PropertyAttributes { writable: false, enumerable: false, configurable: false },
807 );
808 let throw_type_err = Obj::native("", |it: &mut Interp, _: Value, _: &[Value]| {
809 Err(it.type_error("'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them"))
810 });
811 {
812 let mut tb = throw_type_err.borrow_mut();
813 tb.props.insert("length".into(), Value::Number(0.0));
814 tb.props.insert("name".into(), Value::str(""));
815 tb.delete_virtual_fn_prop("length");
816 tb.delete_virtual_fn_prop("name");
817 let non_cfg = PropertyAttributes { writable: false, enumerable: false, configurable: false };
818 tb.insert_attr("length", non_cfg);
819 tb.insert_attr("name", non_cfg);
820 tb.set_frozen(true);
821 }
822 let tte_val = Value::Object(throw_type_err);
823 fp.insert_accessor("caller", Accessor { get: Some(tte_val.clone()), set: Some(tte_val.clone()) });
824 fp.insert_attr("caller", PropertyAttributes { writable: false, enumerable: false, configurable: true });
825 fp.insert_accessor("arguments", Accessor { get: Some(tte_val.clone()), set: Some(tte_val) });
826 fp.insert_attr("arguments", PropertyAttributes { writable: false, enumerable: false, configurable: true });
827 }
828 let subtypes: [(&str, &str, NativeFn); 3] = [
829 ("%AsyncFunction", "AsyncFunction", props_methods::async_function_ctor),
830 ("%GeneratorFunction", "GeneratorFunction", props_methods::generator_function_ctor),
831 ("%AsyncGeneratorFunction", "AsyncGeneratorFunction", props_methods::async_generator_function_ctor),
832 ];
833 for (var, name, f) in subtypes {
834 let c = nv(name, f);
835 let p = Obj::plain();
836 {
837 let mut pb = p.borrow_mut();
838 pb.proto = Some(function_proto.clone());
839 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str(name));
840 }
841 if let Value::Object(co) = &c {
842 let mut cb = co.borrow_mut();
843 cb.props.insert("prototype".into(), Value::Object(p.clone()));
844 cb.insert_attr(
845 "prototype",
846 PropertyAttributes { writable: false, enumerable: false, configurable: false },
847 );
848 }
849 p.borrow_mut().props.insert("constructor".into(), c.clone());
850 p.borrow_mut().hide_props(&["constructor", "Symbol(Symbol.toStringTag)"]);
851 g.vars.insert(var.into(), c);
852 }
853 fc.borrow_mut().props.insert("prototype".into(), Value::Object(function_proto));
854 }
855 g.vars.insert("Function".into(), function_ctor_v);
856
857 let ab_ctor = nv("ArrayBuffer", arraybuffer_ctor);
859 {
860 let ab_proto = Obj::plain();
861 {
862 let mut ap = ab_proto.borrow_mut();
863 ap.proto = Some(object_proto.clone());
864 ap.props.insert("constructor".into(), ab_ctor.clone());
865 ap.insert_attr(
866 "constructor",
867 PropertyAttributes { writable: true, enumerable: false, configurable: true },
868 );
869 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
870 let bl_get = nv("get byteLength", ab_get_byte_length);
871 ap.insert_accessor("byteLength", Accessor { get: Some(bl_get), set: None });
872 ap.insert_attr("byteLength", acc_attr);
873 let mbl_get = nv("get maxByteLength", ab_get_max_byte_length);
874 ap.insert_accessor("maxByteLength", Accessor { get: Some(mbl_get), set: None });
875 ap.insert_attr("maxByteLength", acc_attr);
876 let res_get = nv("get resizable", ab_get_resizable);
877 ap.insert_accessor("resizable", Accessor { get: Some(res_get), set: None });
878 ap.insert_attr("resizable", acc_attr);
879 let det_get = nv("get detached", ab_get_detached);
880 ap.insert_accessor("detached", Accessor { get: Some(det_get), set: None });
881 ap.insert_attr("detached", acc_attr);
882 let imm_get = nv("get immutable", ab_get_immutable);
883 ap.insert_accessor("immutable", Accessor { get: Some(imm_get), set: None });
884 ap.insert_attr("immutable", acc_attr);
885 ap.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("ArrayBuffer"));
886 ap.insert_attr(
887 "Symbol(Symbol.toStringTag)",
888 PropertyAttributes { writable: false, enumerable: false, configurable: true },
889 );
890 }
891 if let Value::Object(o) = &ab_ctor {
892 o.borrow_mut().props.insert("isView".into(), nv("isView", arraybuffer_is_view));
893 o.borrow_mut().props.insert("prototype".into(), Value::Object(ab_proto));
894 o.borrow_mut().insert_attr(
895 "prototype",
896 PropertyAttributes { writable: false, enumerable: false, configurable: false },
897 );
898 }
899 }
900 g.vars.insert("ArrayBuffer".into(), ab_ctor);
901
902 let sab_ctor = nv("SharedArrayBuffer", shared_arraybuffer_ctor);
903 {
904 let sab_proto = Obj::plain();
905 {
906 let mut sp = sab_proto.borrow_mut();
907 sp.proto = Some(object_proto.clone());
908 sp.props.insert("constructor".into(), sab_ctor.clone());
909 sp.insert_attr(
910 "constructor",
911 PropertyAttributes { writable: true, enumerable: false, configurable: true },
912 );
913 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
914 let bl_get = nv("get byteLength", sab_get_byte_length);
915 sp.insert_accessor("byteLength", Accessor { get: Some(bl_get), set: None });
916 sp.insert_attr("byteLength", acc_attr);
917 let mbl_get = nv("get maxByteLength", sab_get_max_byte_length);
918 sp.insert_accessor("maxByteLength", Accessor { get: Some(mbl_get), set: None });
919 sp.insert_attr("maxByteLength", acc_attr);
920 let gr_get = nv("get growable", sab_get_growable);
921 sp.insert_accessor("growable", Accessor { get: Some(gr_get), set: None });
922 sp.insert_attr("growable", acc_attr);
923 sp.props.insert("grow".into(), nv("grow", sab_grow));
924 sp.props.insert("slice".into(), nv("slice", sab_slice));
925 sp.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("SharedArrayBuffer"));
926 sp.insert_attr(
927 "Symbol(Symbol.toStringTag)",
928 PropertyAttributes { writable: false, enumerable: false, configurable: true },
929 );
930 }
931 if let Value::Object(sc) = &sab_ctor {
932 sc.borrow_mut().props.insert("prototype".into(), Value::Object(sab_proto));
933 sc.borrow_mut().insert_attr(
934 "prototype",
935 PropertyAttributes { writable: false, enumerable: false, configurable: false },
936 );
937 }
938 }
939 g.vars.insert("SharedArrayBuffer".into(), sab_ctor);
940
941 let atomics_obj = Obj::plain();
942 {
943 let mut ab = atomics_obj.borrow_mut();
944 ab.proto = Some(object_proto.clone());
945 ab.props.insert("add".into(), nv("Atomics.add", atomics_add));
946 ab.props.insert("and".into(), nv("Atomics.and", atomics_and));
947 ab.props.insert("compareExchange".into(), nv("Atomics.compareExchange", atomics_compare_exchange));
948 ab.props.insert("exchange".into(), nv("Atomics.exchange", atomics_exchange));
949 ab.props.insert("isLockFree".into(), nv("Atomics.isLockFree", atomics_is_lock_free));
950 ab.props.insert("load".into(), nv("Atomics.load", atomics_load));
951 ab.props.insert("notify".into(), nv("Atomics.notify", atomics_notify));
952 ab.props.insert("or".into(), nv("Atomics.or", atomics_or));
953 ab.props.insert("pause".into(), nv("Atomics.pause", atomics_pause));
954 ab.props.insert("store".into(), nv("Atomics.store", atomics_store));
955 ab.props.insert("sub".into(), nv("Atomics.sub", atomics_sub));
956 ab.props.insert("wait".into(), nv("Atomics.wait", atomics_wait));
957 ab.props.insert("xor".into(), nv("Atomics.xor", atomics_xor));
958 }
959 g.vars.insert("Atomics".into(), Value::Object(atomics_obj));
960
961 let ds_ctor = nv("DisposableStack", disposable_stack_ctor);
963 {
964 let ds_proto = Obj::plain();
965 {
966 let mut dp = ds_proto.borrow_mut();
967 dp.proto = Some(object_proto.clone());
968 dp.props.insert("constructor".into(), ds_ctor.clone());
969 dp.insert_attr(
970 "constructor",
971 PropertyAttributes { writable: true, enumerable: false, configurable: true },
972 );
973 let disp_get = nv("get disposed", ds_get_disposed);
974 dp.insert_accessor("disposed", Accessor { get: Some(disp_get), set: None });
975 dp.insert_attr(
976 "disposed",
977 PropertyAttributes { writable: false, enumerable: false, configurable: true },
978 );
979 let dispose_fn = nv("dispose", ds_dispose);
980 dp.props.insert("dispose".into(), dispose_fn.clone());
981 dp.props.insert("Symbol(Symbol.dispose)".into(), dispose_fn);
982 dp.props.insert("use".into(), nv("DisposableStack.use", ds_use));
983 dp.props.insert("adopt".into(), nv("DisposableStack.adopt", ds_adopt));
984 dp.props.insert("defer".into(), nv("DisposableStack.defer", ds_defer));
985 dp.props.insert("move".into(), nv("move", ds_move));
986 dp.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("DisposableStack"));
987 dp.insert_attr(
988 "Symbol(Symbol.toStringTag)",
989 PropertyAttributes { writable: false, enumerable: false, configurable: true },
990 );
991 }
992 if let Value::Object(dc) = &ds_ctor {
993 dc.borrow_mut().props.insert("prototype".into(), Value::Object(ds_proto));
994 dc.borrow_mut().insert_attr(
995 "prototype",
996 PropertyAttributes { writable: false, enumerable: false, configurable: false },
997 );
998 }
999 }
1000 g.vars.insert("DisposableStack".into(), ds_ctor);
1001
1002 let ads_ctor = nv("AsyncDisposableStack", async_disposable_stack_ctor);
1003 {
1004 let ads_proto = Obj::plain();
1005 {
1006 let mut ap = ads_proto.borrow_mut();
1007 ap.proto = Some(object_proto.clone());
1008 ap.props.insert("constructor".into(), ads_ctor.clone());
1009 ap.insert_attr(
1010 "constructor",
1011 PropertyAttributes { writable: true, enumerable: false, configurable: true },
1012 );
1013 let disp_get = nv("get disposed", ads_get_disposed);
1014 ap.insert_accessor("disposed", Accessor { get: Some(disp_get), set: None });
1015 ap.insert_attr(
1016 "disposed",
1017 PropertyAttributes { writable: false, enumerable: false, configurable: true },
1018 );
1019 let dispose_async_fn = nv("disposeAsync", ads_dispose_async);
1020 ap.props.insert("disposeAsync".into(), dispose_async_fn.clone());
1021 ap.props.insert("Symbol(Symbol.asyncDispose)".into(), dispose_async_fn);
1022 ap.props.insert("use".into(), nv("AsyncDisposableStack.use", ads_use));
1023 ap.props.insert("adopt".into(), nv("AsyncDisposableStack.adopt", ads_adopt));
1024 ap.props.insert("defer".into(), nv("AsyncDisposableStack.defer", ads_defer));
1025 ap.props.insert("move".into(), nv("move", ads_move));
1026 ap.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("AsyncDisposableStack"));
1027 ap.insert_attr(
1028 "Symbol(Symbol.toStringTag)",
1029 PropertyAttributes { writable: false, enumerable: false, configurable: true },
1030 );
1031 }
1032 if let Value::Object(ac) = &ads_ctor {
1033 ac.borrow_mut().props.insert("prototype".into(), Value::Object(ads_proto));
1034 ac.borrow_mut().insert_attr(
1035 "prototype",
1036 PropertyAttributes { writable: false, enumerable: false, configurable: false },
1037 );
1038 }
1039 }
1040 g.vars.insert("AsyncDisposableStack".into(), ads_ctor);
1041
1042 let typed_array_ctor = Obj::native("TypedArray", |it: &mut Interp, _: Value, _: &[Value]| {
1043 Err(it.type_error("Abstract class TypedArray not directly constructable"))
1044 });
1045 let typed_array_proto = Obj::plain();
1046 {
1047 let mut tp = typed_array_proto.borrow_mut();
1048 tp.proto = Some(object_proto.clone());
1049 tp.props.insert("constructor".into(), Value::Object(typed_array_ctor.clone()));
1050 let ta_buffer_get = nv("get buffer", ta_buffer_get);
1051 let ta_byte_length_get = nv("get byteLength", ta_byte_length_get);
1052 let ta_byte_offset_get = nv("get byteOffset", ta_byte_offset_get);
1053 let ta_length_get = nv("get length", ta_length_get);
1054 let ta_tag_get = nv("get [Symbol.toStringTag]", ta_to_string_tag_get);
1055 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
1056 let meth_attr = PropertyAttributes { writable: true, enumerable: false, configurable: true };
1057 let const_attr = PropertyAttributes { writable: false, enumerable: false, configurable: false };
1058 tp.insert_accessor("buffer", Accessor { get: Some(ta_buffer_get), set: None });
1059 tp.insert_attr("buffer", acc_attr);
1060 tp.insert_accessor("byteLength", Accessor { get: Some(ta_byte_length_get), set: None });
1061 tp.insert_attr("byteLength", acc_attr);
1062 tp.insert_accessor("byteOffset", Accessor { get: Some(ta_byte_offset_get), set: None });
1063 tp.insert_attr("byteOffset", acc_attr);
1064 tp.insert_accessor("length", Accessor { get: Some(ta_length_get), set: None });
1065 tp.insert_attr("length", acc_attr);
1066 tp.insert_accessor("Symbol(Symbol.toStringTag)", Accessor { get: Some(ta_tag_get), set: None });
1067 tp.insert_attr("Symbol(Symbol.toStringTag)", acc_attr);
1068
1069 let methods: &[(&str, NativeFn)] = &[
1070 ("at", ta_at),
1071 ("copyWithin", ta_copy_within),
1072 ("entries", ta_entries),
1073 ("every", ta_every),
1074 ("fill", ta_fill),
1075 ("filter", ta_filter),
1076 ("find", ta_find),
1077 ("findIndex", ta_find_index),
1078 ("findLast", ta_find_last),
1079 ("findLastIndex", ta_find_last_index),
1080 ("forEach", ta_for_each),
1081 ("includes", ta_includes),
1082 ("indexOf", ta_index_of),
1083 ("join", ta_join),
1084 ("keys", ta_keys),
1085 ("lastIndexOf", ta_last_index_of),
1086 ("map", ta_map),
1087 ("reduce", ta_reduce),
1088 ("reduceRight", ta_reduce_right),
1089 ("reverse", ta_reverse),
1090 ("set", ta_set),
1091 ("slice", ta_slice),
1092 ("some", ta_some),
1093 ("sort", ta_sort),
1094 ("subarray", ta_subarray),
1095 ("toReversed", ta_to_reversed),
1096 ("toSorted", ta_to_sorted),
1097 ("with", ta_with),
1098 ];
1099 for &(mname, mfn) in methods {
1100 tp.props.insert(mname.into(), nv(mname, mfn));
1101 tp.insert_attr(mname, meth_attr);
1102 }
1103 let values_fn = nv("values", ta_values);
1104 tp.props.insert("values".into(), values_fn.clone());
1105 tp.insert_attr("values", meth_attr);
1106 tp.props.insert("Symbol(Symbol.iterator)".into(), values_fn);
1107 tp.insert_attr("Symbol(Symbol.iterator)", meth_attr);
1108 let arr_to_str = g.vars.get("Array").and_then(|av| {
1109 if let Value::Object(ao) = av {
1110 if let Some(Value::Object(ap)) = ao.borrow().props.get("prototype") {
1111 return ap.borrow().props.get("toString").cloned();
1112 }
1113 }
1114 None
1115 }).unwrap_or_else(|| nv("toString", arr_to_string));
1116 tp.props.insert("toString".into(), arr_to_str);
1117 tp.insert_attr("toString", meth_attr);
1118 tp.props.insert(
1119 "toLocaleString".into(),
1120 nv("toLocaleString", ta_to_locale_string),
1121 );
1122 tp.insert_attr("toLocaleString", meth_attr);
1123 tp.insert_attr("constructor", meth_attr);
1124
1125 let mut tb = typed_array_ctor.borrow_mut();
1126 tb.props.insert("from".into(), nv("from", uint8array_from));
1127 tb.props.insert("of".into(), nv("of", typed_array_of));
1128 tb.props.insert("prototype".into(), Value::Object(typed_array_proto.clone()));
1129 tb.insert_attr("from", meth_attr);
1130 tb.insert_attr("of", meth_attr);
1131 tb.insert_attr("prototype", const_attr);
1132 tb.insert_accessor(
1133 "Symbol(Symbol.species)",
1134 Accessor { get: Some(nv("get [Symbol.species]", symbol_species_getter)), set: None },
1135 );
1136 tb.insert_attr("Symbol(Symbol.species)", acc_attr);
1137 }
1138 let mut register_typed_array = |name: &str, ctor: NativeFn, _from_fn: NativeFn| {
1139 let f = nv(name, ctor);
1140 let const_attr = PropertyAttributes { writable: false, enumerable: false, configurable: false };
1141 let hidden_attr = PropertyAttributes { writable: true, enumerable: false, configurable: true };
1142 if let Value::Object(o) = &f {
1143 let mut ob = o.borrow_mut();
1144 ob.proto = Some(typed_array_ctor.clone());
1145 let elem = match name {
1147 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" => 1.0,
1148 "Int16Array" | "Uint16Array" | "Float16Array" => 2.0,
1149 "Int32Array" | "Uint32Array" | "Float32Array" => 4.0,
1150 _ => 8.0,
1151 };
1152 ob.props.insert("BYTES_PER_ELEMENT".into(), Value::Number(elem));
1153 ob.insert_attr("BYTES_PER_ELEMENT", const_attr);
1154 let proto = Obj::plain();
1155 {
1156 let mut pb = proto.borrow_mut();
1157 pb.props.insert("BYTES_PER_ELEMENT".into(), Value::Number(elem));
1158 pb.insert_attr("BYTES_PER_ELEMENT", const_attr);
1159 pb.proto = Some(typed_array_proto.clone());
1160 pb.props.insert("constructor".into(), f.clone());
1161 pb.insert_attr("constructor", hidden_attr);
1162 }
1163 ob.props.insert("prototype".into(), Value::Object(proto));
1164 ob.insert_attr("prototype", const_attr);
1165 }
1166 g.vars.insert(name.into(), f);
1167 };
1168 register_typed_array("Uint8Array", uint8array_ctor, uint8array_from);
1169 register_typed_array("Int8Array", int8array_ctor, int8array_from);
1170 register_typed_array("Uint8ClampedArray", uint8clampedarray_ctor, uint8clampedarray_from);
1171 register_typed_array("Int16Array", int16array_ctor, int16array_from);
1172 register_typed_array("Uint16Array", uint16array_ctor, uint16array_from);
1173 register_typed_array("Int32Array", int32array_ctor, int32array_from);
1174 register_typed_array("Uint32Array", uint32array_ctor, uint32array_from);
1175 register_typed_array("Float16Array", float16array_ctor, float16array_from);
1176 register_typed_array("Float32Array", float32array_ctor, float32array_from);
1177 register_typed_array("Float64Array", float64array_ctor, float64array_from);
1178 register_typed_array("BigInt64Array", bigint64array_ctor, bigint64array_from);
1179 register_typed_array("BigUint64Array", biguint64array_ctor, biguint64array_from);
1180 if let Some(Value::Object(u8a)) = g.vars.get("Uint8Array").cloned() {
1181 let mut b = u8a.borrow_mut();
1182 b.props.insert("fromBase64".into(), nv("fromBase64", ta_from_base64));
1183 b.props.insert("fromHex".into(), nv("fromHex", ta_from_hex));
1184 }
1185 let dv_ctor = nv("DataView", dataview_ctor);
1186 {
1187 let dv_proto = Obj::plain();
1188 {
1189 let mut dp = dv_proto.borrow_mut();
1190 dp.proto = Some(object_proto.clone());
1191 dp.props.insert("constructor".into(), dv_ctor.clone());
1192 dp.insert_attr(
1193 "constructor",
1194 PropertyAttributes { writable: true, enumerable: false, configurable: true },
1195 );
1196 let acc_attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
1197 let buf_get = nv("get buffer", dv_get_buffer);
1198 dp.insert_accessor("buffer", Accessor { get: Some(buf_get), set: None });
1199 dp.insert_attr("buffer", acc_attr);
1200 let bl_get = nv("get byteLength", dv_get_byte_length);
1201 dp.insert_accessor("byteLength", Accessor { get: Some(bl_get), set: None });
1202 dp.insert_attr("byteLength", acc_attr);
1203 let bo_get = nv("get byteOffset", dv_get_byte_offset);
1204 dp.insert_accessor("byteOffset", Accessor { get: Some(bo_get), set: None });
1205 dp.insert_attr("byteOffset", acc_attr);
1206 dp.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("DataView"));
1207 dp.insert_attr(
1208 "Symbol(Symbol.toStringTag)",
1209 PropertyAttributes { writable: false, enumerable: false, configurable: true },
1210 );
1211 }
1212 if let Value::Object(dc) = &dv_ctor {
1213 dc.borrow_mut().props.insert("prototype".into(), Value::Object(dv_proto));
1214 dc.borrow_mut().insert_attr(
1215 "prototype",
1216 PropertyAttributes { writable: false, enumerable: false, configurable: false },
1217 );
1218 }
1219 }
1220 g.vars.insert("DataView".into(), dv_ctor);
1221
1222 let map_ctor_v = nv("Map", map_ctor);
1224 if let Value::Object(mc) = &map_ctor_v {
1225 mc.borrow_mut().props.insert("groupBy".into(), nv("Map.groupBy", map_group_by));
1226 }
1227 g.vars.insert("Map".into(), map_ctor_v);
1228 g.vars.insert("Set".into(), nv("Set", set_ctor));
1229
1230 let promise_ctor_v = nv("Promise", promise_ctor);
1232 if let Value::Object(pc) = &promise_ctor_v {
1233 let mut b = pc.borrow_mut();
1234 b.props.insert("resolve".into(), nv("Promise.resolve", promise_resolve_static));
1235 b.props.insert("reject".into(), nv("Promise.reject", promise_reject_static));
1236 b.props.insert("all".into(), nv("Promise.all", promise_all_static));
1237 b.props.insert("allSettled".into(), nv("Promise.allSettled", promise_all_settled_static));
1238 b.props.insert("allKeyed".into(), nv("Promise.allKeyed", promise_all_keyed_static));
1239 b.props.insert("allSettledKeyed".into(), nv("Promise.allSettledKeyed", promise_all_settled_keyed_static));
1240 b.props.insert("race".into(), nv("Promise.race", promise_race_static));
1241 b.props.insert("any".into(), nv("Promise.any", promise_any_static));
1242 b.props.insert("withResolvers".into(), nv("Promise.withResolvers", promise_with_resolvers_static));
1243 b.props.insert("try".into(), nv("Promise.try", promise_try_static));
1244 }
1245 g.vars.insert("Promise".into(), promise_ctor_v);
1246
1247 let proxy_ctor_v = nv("Proxy", proxy_ctor);
1249 if let Value::Object(pc) = &proxy_ctor_v {
1250 pc.borrow_mut().props.insert("revocable".into(), nv("Proxy.revocable", proxy_revocable));
1251 }
1252 g.vars.insert("Proxy".into(), proxy_ctor_v);
1253 let reflect = Obj::plain();
1254 {
1255 let mut r = reflect.borrow_mut();
1256 r.props.insert("get".into(), nv("Reflect.get", reflect_get));
1257 r.props.insert("set".into(), nv("Reflect.set", reflect_set));
1258 r.props.insert("has".into(), nv("Reflect.has", reflect_has));
1259 r.props.insert("deleteProperty".into(), nv("Reflect.deleteProperty", reflect_delete_property));
1260 r.props.insert("ownKeys".into(), nv("Reflect.ownKeys", reflect_own_keys));
1261 r.props.insert("getPrototypeOf".into(), nv("Reflect.getPrototypeOf", reflect_get_prototype_of));
1262 r.props.insert("defineProperty".into(), nv("Reflect.defineProperty", reflect_define_property));
1263 r.props.insert("apply".into(), nv("Reflect.apply", reflect_apply));
1264 r.props.insert("construct".into(), nv("Reflect.construct", reflect_construct));
1265 r.props.insert("setPrototypeOf".into(), nv("Reflect.setPrototypeOf", reflect_set_prototype_of));
1266 r.props.insert("isExtensible".into(), nv("Reflect.isExtensible", reflect_is_extensible));
1267 r.props.insert("preventExtensions".into(), nv("Reflect.preventExtensions", reflect_prevent_extensions));
1268 r.props.insert("getOwnPropertyDescriptor".into(), nv("Reflect.getOwnPropertyDescriptor", reflect_get_own_property_descriptor));
1269 }
1270 g.vars.insert("Reflect".into(), Value::Object(reflect));
1271
1272 let iterator_ctor = nv("Iterator", iterator_ctor);
1273 if let Value::Object(ic) = &iterator_ctor {
1274 let mut b = ic.borrow_mut();
1275 b.props.insert("from".into(), nv("Iterator.from", iterator_from));
1276 b.props.insert("range".into(), nv("Iterator.range", iterator_range));
1277 b.props.insert("concat".into(), nv("Iterator.concat", iterator_concat_static));
1278 b.props.insert("zip".into(), nv("Iterator.zip", iterator_zip_static));
1279 b.props.insert("zipKeyed".into(), nv("Iterator.zipKeyed", iterator_zip_keyed_static));
1280 }
1281 g.vars.insert("Iterator".into(), iterator_ctor);
1282
1283 g.vars.insert("setTimeout".into(), nv("setTimeout", set_timeout));
1285 g.vars.insert("setInterval".into(), nv("setInterval", set_interval));
1286 g.vars.insert("clearTimeout".into(), nv("clearTimeout", clear_timeout));
1287 g.vars.insert("clearInterval".into(), nv("clearInterval", clear_interval));
1288 g.vars.insert("queueMicrotask".into(), nv("queueMicrotask", queue_microtask));
1289
1290 let date_ctor_obj = Obj::native("Date", date_ctor);
1292 {
1293 let mut b = date_ctor_obj.borrow_mut();
1294 b.props.insert("now".into(), nv("Date.now", date_now_static));
1295 b.props.insert("parse".into(), nv("Date.parse", date_parse_static));
1296 b.props.insert("UTC".into(), nv("Date.UTC", date_utc_static));
1297 }
1298 g.vars.insert("Date".into(), Value::Object(date_ctor_obj));
1299
1300 let error_proto = Obj::plain();
1302 {
1303 let mut b = error_proto.borrow_mut();
1304 b.props.insert("name".into(), Value::str("Error"));
1305 b.props.insert("message".into(), Value::str(""));
1306 }
1307 let error_ctor_obj = Obj::native("Error", error_ctor);
1308 error_ctor_obj.borrow_mut().props.insert("prototype".into(), Value::Object(error_proto.clone()));
1309 error_proto.borrow_mut().props.insert("constructor".into(), Value::Object(error_ctor_obj.clone()));
1310 error_proto.borrow_mut().props.insert("toString".into(), nv("toString", error_proto_to_string));
1311 error_proto.borrow_mut().insert_accessor(
1312 "stack",
1313 Accessor {
1314 get: Some(nv("get stack", error_stack_get)),
1315 set: Some(nv("set stack", error_stack_set)),
1316 },
1317 );
1318 error_proto.borrow_mut().insert_attr(
1319 "stack",
1320 PropertyAttributes { writable: false, enumerable: false, configurable: true },
1321 );
1322 error_proto.borrow_mut().hide_props(&["name", "message", "constructor", "toString"]);
1323 {
1324 let mut b = error_ctor_obj.borrow_mut();
1325 b.props.insert("isError".into(), nv("Error.isError", error_is_error));
1326 b.props.insert("captureStackTrace".into(), nv("Error.captureStackTrace", error_capture_stack_trace));
1327 b.props.insert("stackTraceLimit".into(), Value::Number(10.0));
1328 }
1329 g.vars.insert("Error".into(), Value::Object(error_ctor_obj.clone()));
1330
1331 fn make_error_subtype(
1332 name: &str,
1333 error_proto: &ObjRef,
1334 error_ctor: &ObjRef,
1335 ctor_fn: NativeFn,
1336 ) -> Value {
1337 let proto = Obj::plain();
1338 proto.borrow_mut().proto = Some(error_proto.clone());
1339 proto.borrow_mut().props.insert("name".into(), Value::str(name));
1340 let ctor_obj = Obj::native(name, ctor_fn);
1341 ctor_obj.borrow_mut().proto = Some(error_ctor.clone());
1342 ctor_obj.borrow_mut().props.insert("prototype".into(), Value::Object(proto.clone()));
1343 proto.borrow_mut().props.insert("constructor".into(), Value::Object(ctor_obj.clone()));
1344 proto.borrow_mut().hide_props(&["name", "constructor"]);
1345 Value::Object(ctor_obj)
1346 }
1347 g.vars.insert("TypeError".into(), make_error_subtype("TypeError", &error_proto, &error_ctor_obj, type_error_ctor));
1348 g.vars.insert("RangeError".into(), make_error_subtype("RangeError", &error_proto, &error_ctor_obj, range_error_ctor));
1349 g.vars.insert("SyntaxError".into(), make_error_subtype("SyntaxError", &error_proto, &error_ctor_obj, syntax_error_ctor));
1350 g.vars.insert("ReferenceError".into(), make_error_subtype("ReferenceError", &error_proto, &error_ctor_obj, reference_error_ctor));
1351 g.vars.insert("EvalError".into(), make_error_subtype("EvalError", &error_proto, &error_ctor_obj, eval_error_ctor));
1352 g.vars.insert("URIError".into(), make_error_subtype("URIError", &error_proto, &error_ctor_obj, uri_error_ctor));
1353 g.vars.insert("SuppressedError".into(), make_error_subtype("SuppressedError", &error_proto, &error_ctor_obj, suppressed_error_ctor));
1354 g.vars.insert("AggregateError".into(), make_error_subtype("AggregateError", &error_proto, &error_ctor_obj, aggregate_error_ctor));
1355
1356 g.vars.insert("FinalizationRegistry".into(), nv("FinalizationRegistry", finalization_registry_ctor));
1358
1359 let regexp_ctor_v = nv("RegExp", regexp_ctor);
1361 if let Value::Object(rc) = ®exp_ctor_v {
1362 rc.borrow_mut().props.insert("escape".into(), nv("RegExp.escape", regexp_escape_static));
1363 install_regexp_legacy_accessors(rc);
1364 let proto = Obj::plain();
1365 {
1366 let mut pb = proto.borrow_mut();
1367 install_regexp_proto(&mut pb);
1368 pb.props.insert("constructor".into(), regexp_ctor_v.clone());
1369 pb.insert_attr("constructor", PropertyAttributes { writable: true, configurable: true, enumerable: false });
1370 pb.proto = Some(object_proto.clone());
1371 }
1372 rc.borrow_mut().insert_attr("prototype", PropertyAttributes { writable: false, configurable: false, enumerable: false });
1373 rc.borrow_mut().props.insert("prototype".into(), Value::Object(proto));
1374 }
1375 g.vars.insert("RegExp".into(), regexp_ctor_v);
1376
1377 g.vars.insert("WeakMap".into(), nv("WeakMap", weakmap_ctor));
1379 g.vars.insert("WeakSet".into(), nv("WeakSet", weakset_ctor));
1380 g.vars.insert("WeakRef".into(), nv("WeakRef", weakref_ctor));
1381
1382 {
1384 let sym_fn = nv("Symbol", symbol_fn);
1385 if let Value::Object(sf) = &sym_fn {
1386 let mut b = sf.borrow_mut();
1387 b.props.insert("for".into(), nv("Symbol.for", symbol_for));
1388 b.props.insert("keyFor".into(), nv("Symbol.keyFor", symbol_key_for));
1389 b.props.insert("iterator".into(), Value::str("Symbol(Symbol.iterator)"));
1390 b.props.insert("toPrimitive".into(), Value::str("Symbol(Symbol.toPrimitive)"));
1391 b.props.insert("hasInstance".into(), Value::str("Symbol(Symbol.hasInstance)"));
1392 b.props.insert("toStringTag".into(), Value::str("Symbol(Symbol.toStringTag)"));
1393 b.props.insert("asyncIterator".into(), Value::str("Symbol(Symbol.asyncIterator)"));
1394 b.props.insert("isConcatSpreadable".into(), Value::str("Symbol(Symbol.isConcatSpreadable)"));
1395 for name in [
1396 "species",
1397 "unscopables",
1398 "match",
1399 "matchAll",
1400 "replace",
1401 "search",
1402 "split",
1403 ] {
1404 b.props.insert(String::from(name).into(), Value::str(format!("Symbol(Symbol.{})", name)));
1405 }
1406 b.props.insert("dispose".into(), Value::str("Symbol(Symbol.dispose)"));
1407 b.props.insert("asyncDispose".into(), Value::str("Symbol(Symbol.asyncDispose)"));
1408 let sym_proto = Obj::plain();
1409 {
1410 let mut sp = sym_proto.borrow_mut();
1411 sp.proto = Some(object_proto.clone());
1412 sp.props.insert("constructor".into(), Value::Object(sf.clone()));
1413 sp.props.insert(
1414 "valueOf".into(),
1415 nv("valueOf", |it: &mut Interp, this: Value, _a: &[Value]| {
1416 match &this {
1417 Value::Str(s) if s.starts_with("Symbol(") && s.ends_with(')') => {
1418 Ok(this)
1419 }
1420 Value::Object(o) => {
1421 if let Some(p @ Value::Str(s)) = o.borrow().primitive() {
1422 if s.starts_with("Symbol(") && s.ends_with(')') {
1423 return Ok(p.clone());
1424 }
1425 }
1426 Err(it.type_error("Symbol.prototype.valueOf requires that 'this' be a Symbol"))
1427 }
1428 _ => Err(it.type_error("Symbol.prototype.valueOf requires that 'this' be a Symbol")),
1429 }
1430 }),
1431 );
1432 sp.props.insert(
1433 "toString".into(),
1434 nv("toString", |it: &mut Interp, this: Value, _a: &[Value]| {
1435 let sym = match &this {
1436 Value::Str(s) if s.starts_with("Symbol(") && s.ends_with(')') => Some(this.clone()),
1437 Value::Object(o) => match o.borrow().primitive() {
1438 Some(p @ Value::Str(s)) if s.starts_with("Symbol(") && s.ends_with(')') => Some(p.clone()),
1439 _ => None,
1440 },
1441 _ => None,
1442 };
1443 match sym {
1444 Some(v) => Ok(v),
1445 None => Err(it.type_error("Symbol.prototype.toString requires that 'this' be a Symbol")),
1446 }
1447 }),
1448 );
1449 sp.hide_props(&["constructor", "valueOf", "toString"]);
1450 }
1451 b.props.insert("prototype".into(), Value::Object(sym_proto));
1452 }
1453 g.vars.insert("Symbol".into(), sym_fn);
1454
1455 let species_fn = nv("get [Symbol.species]", symbol_species_getter);
1456 for ctor_name in [
1457 "Array", "RegExp", "Promise", "Map", "Set", "ArrayBuffer", "SharedArrayBuffer",
1458 ] {
1459 if let Some(Value::Object(ctor_obj)) = g.vars.get(ctor_name).cloned() {
1460 ctor_obj.borrow_mut().insert_accessor(
1461 "Symbol(Symbol.species)",
1462 Accessor { get: Some(species_fn.clone()), set: None },
1463 );
1464 ctor_obj.borrow_mut().insert_attr(
1465 "Symbol(Symbol.species)",
1466 PropertyAttributes { writable: false, configurable: true, enumerable: false },
1467 );
1468 }
1469 }
1470 }
1471
1472 g.vars.insert("NaN".into(), Value::Number(f64::NAN));
1474 g.vars.insert("Infinity".into(), Value::Number(f64::INFINITY));
1475 g.vars.insert("undefined".into(), Value::Undefined);
1476 let global_obj = Obj::plain();
1477 global_obj.borrow_mut().proto = Some(object_proto.clone());
1478 g.vars.insert("globalThis".into(), Value::Object(global_obj));
1479 }
1480 ensure_ctor_prototypes(global);
1481}
1482
1483pub(crate) mod atomics;
1484pub(crate) mod collections;
1485pub(crate) mod console_math_json;
1486pub(crate) mod date;
1487pub(crate) mod disposable;
1488pub(crate) mod encoding;
1489pub(crate) mod errors_misc;
1490pub(crate) mod extra_methods;
1491pub(crate) mod iter_helpers;
1492pub(crate) mod extra_static;
1493pub(crate) mod intl;
1494pub(crate) mod intl_locale;
1495pub(crate) mod object_array;
1496pub(crate) mod promise;
1497pub(crate) mod props_methods;
1498pub(crate) mod regexp;
1499pub(crate) mod regexp_proto;
1500pub(crate) mod timers_gen;
1501pub(crate) mod typed_array;
1502pub(crate) mod weak_symbol;
1503
1504pub(crate) use atomics::*;
1505pub(crate) use collections::*;
1506pub(crate) use console_math_json::*;
1507pub(crate) use date::*;
1508pub(crate) use disposable::*;
1509pub(crate) use encoding::*;
1510pub(crate) use errors_misc::*;
1511pub(crate) use extra_methods::*;
1512pub(crate) use extra_static::*;
1513pub(crate) use intl::*;
1514pub(crate) use iter_helpers::*;
1515pub(crate) use object_array::*;
1516pub(crate) use promise::*;
1517pub(crate) use props_methods::*;
1518pub(crate) use regexp::*;
1519pub(crate) use regexp_proto::*;
1520pub(crate) use timers_gen::*;
1521pub(crate) use typed_array::*;
1522pub(crate) use weak_symbol::*;