1use super::*;
4use crate::os_lib::ecma::host::HostOwn;
5
6pub(crate) fn string_from_char_code(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
8 let a: &[Value] = &prim_num_args(it, a)?;
9 if a.len() == 1 {
10 let unit = (crate::os_lib::ecma::interp::to_u32(a[0].to_number()) & 0xFFFF) as u16;
11 return Ok(it.char_unit_val(Some(unit)));
12 }
13 let units: Vec<u16> = a
14 .iter()
15 .map(|v| (crate::os_lib::ecma::interp::to_u32(v.to_number()) & 0xFFFF) as u16)
16 .collect();
17 Ok(Value::str(String::from_utf16_lossy(&units)))
18}
19pub(crate) fn string_from_code_point(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
20 let mut s = String::new();
21 for v in a {
22 let n = v.to_number();
23 if !n.is_finite() || n < 0.0 || n > 0x10FFFF as f64 || libm::floor(n) != n {
24 return Err(it.range_error("Invalid code point"));
25 }
26 match char::from_u32(n as u32) {
27 Some(c) => s.push(c),
28 None => s.push('\u{FFFD}'),
30 }
31 }
32 Ok(Value::str(s))
33}
34pub(crate) fn array_of(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
35 Ok(Value::Object(Obj::array(a.to_vec())))
36}
37pub(crate) fn string_raw(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
38 let strings = arg(a, 0);
39 let raw = it.get_property(&strings, "raw").unwrap_or(Value::Undefined);
40 let raw_items: Vec<Value> = match &raw {
41 Value::Object(o) => match &o.borrow().kind {
42 ObjKind::Array(items) => items.clone(),
43 _ => Vec::new(),
44 },
45 _ => Vec::new(),
46 };
47 let mut out = String::new();
48 for (i, r) in raw_items.iter().enumerate() {
49 out.push_str(&r.to_js_string());
50 if let Some(sub) = a.get(i + 1) {
51 out.push_str(&sub.to_js_string());
52 }
53 }
54 Ok(Value::str(out))
55}
56
57pub(crate) fn math_log2(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
59 let a: &[Value] = &prim_num_args(it, a)?;
60 Ok(Value::Number(libm::log2(it.num_of(&arg(a, 0))?)))
61}
62pub(crate) fn math_log10(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
63 let a: &[Value] = &prim_num_args(it, a)?;
64 Ok(Value::Number(libm::log10(it.num_of(&arg(a, 0))?)))
65}
66pub(crate) fn math_cbrt(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
67 let a: &[Value] = &prim_num_args(it, a)?;
68 Ok(Value::Number(libm::cbrt(it.num_of(&arg(a, 0))?)))
69}
70pub(crate) fn math_tan(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
71 let a: &[Value] = &prim_num_args(it, a)?;
72 Ok(Value::Number(libm::tan(it.num_of(&arg(a, 0))?)))
73}
74pub(crate) fn math_atan(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
75 let a: &[Value] = &prim_num_args(it, a)?;
76 Ok(Value::Number(libm::atan(it.num_of(&arg(a, 0))?)))
77}
78pub(crate) fn math_asin(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
79 let a: &[Value] = &prim_num_args(it, a)?;
80 Ok(Value::Number(libm::asin(it.num_of(&arg(a, 0))?)))
81}
82pub(crate) fn math_acos(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
83 let a: &[Value] = &prim_num_args(it, a)?;
84 Ok(Value::Number(libm::acos(it.num_of(&arg(a, 0))?)))
85}
86pub(crate) fn math_atan2(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
87 let a: &[Value] = &prim_num_args(it, a)?;
88 Ok(Value::Number(libm::atan2(
89 it.num_of(&arg(a, 0))?,
90 it.num_of(&arg(a, 1))?,
91 )))
92}
93pub(crate) fn math_hypot(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
94 let a: &[Value] = &prim_num_args(it, a)?;
95 let xs: Vec<f64> = a.iter().map(|v| v.to_number().abs()).collect();
99 if xs.iter().any(|x| x.is_infinite()) {
100 return Ok(Value::Number(f64::INFINITY));
101 }
102 if xs.iter().any(|x| x.is_nan()) {
103 return Ok(Value::Number(f64::NAN));
104 }
105 let max = xs.iter().fold(0.0f64, |m, &x| if x > m { x } else { m });
106 if max == 0.0 {
107 return Ok(Value::Number(0.0));
108 }
109 let (mut sum, mut comp) = (0.0f64, 0.0f64);
110 for &x in &xs {
111 let n = x / max;
112 let summand = n * n - comp;
113 let pre = sum + summand;
114 comp = (pre - sum) - summand;
115 sum = pre;
116 }
117 Ok(Value::Number(libm::sqrt(sum) * max))
118}
119pub(crate) fn math_fround(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
124 let a: &[Value] = &prim_num_args(it, a)?;
125 Ok(Value::Number(it.num_of(&arg(a, 0))? as f32 as f64))
126}
127pub(crate) fn math_f16round(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
130 let a: &[Value] = &prim_num_args(it, a)?;
131 let n = it.num_of(&arg(a, 0))?;
132 let bits = super::typed_array::f64_to_f16_bits(n);
133 Ok(Value::Number(super::typed_array::f16_bits_to_f64(bits)))
134}
135pub(crate) fn math_clamp(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
138 let a: &[Value] = &prim_num_args(it, a)?;
139 let val = it.num_of(&arg(a, 0))?;
140 let min = it.num_of(&arg(a, 1))?;
141 let max = it.num_of(&arg(a, 2))?;
142 if val.is_nan() || min.is_nan() || max.is_nan() || min > max {
143 Ok(Value::Number(f64::NAN))
144 } else {
145 Ok(Value::Number(val.max(min).min(max)))
146 }
147}
148pub(crate) fn math_clz32(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
151 let a: &[Value] = &prim_num_args(it, a)?;
152 let n = it.num_of(&arg(a, 0))?;
153 let u = crate::os_lib::ecma::interp::to_u32(n);
154 Ok(Value::Number(u.leading_zeros() as f64))
155}
156pub(crate) fn math_imul(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
161 let a: &[Value] = &prim_num_args(it, a)?;
162 let x = crate::os_lib::ecma::interp::to_i32(it.num_of(&arg(a, 0))?);
163 let y = crate::os_lib::ecma::interp::to_i32(it.num_of(&arg(a, 1))?);
164 Ok(Value::Number(x.wrapping_mul(y) as f64))
165}
166pub(crate) fn math_sinh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
167 let a: &[Value] = &prim_num_args(it, a)?;
168 Ok(Value::Number(libm::sinh(it.num_of(&arg(a, 0))?)))
169}
170pub(crate) fn math_cosh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
171 let a: &[Value] = &prim_num_args(it, a)?;
172 let x = it.num_of(&arg(a, 0))?;
173 let ax = libm::fabs(x);
175 if (0.34657359027997264..22.0).contains(&ax) {
176 let t = super::console_math_json::v8_exp(ax);
177 return Ok(Value::Number(0.5 * t + 0.5 / t));
178 }
179 Ok(Value::Number(libm::cosh(x)))
180}
181pub(crate) fn math_tanh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
182 let a: &[Value] = &prim_num_args(it, a)?;
183 Ok(Value::Number(libm::tanh(it.num_of(&arg(a, 0))?)))
184}
185pub(crate) fn math_asinh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
186 let a: &[Value] = &prim_num_args(it, a)?;
187 Ok(Value::Number(libm::asinh(it.num_of(&arg(a, 0))?)))
188}
189pub(crate) fn math_acosh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
190 let a: &[Value] = &prim_num_args(it, a)?;
191 Ok(Value::Number(libm::acosh(it.num_of(&arg(a, 0))?)))
192}
193pub(crate) fn math_atanh(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
194 let a: &[Value] = &prim_num_args(it, a)?;
195 Ok(Value::Number(libm::atanh(it.num_of(&arg(a, 0))?)))
196}
197pub(crate) fn math_expm1(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
198 let a: &[Value] = &prim_num_args(it, a)?;
199 Ok(Value::Number(libm::expm1(it.num_of(&arg(a, 0))?)))
200}
201pub(crate) fn math_log1p(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
202 let a: &[Value] = &prim_num_args(it, a)?;
203 Ok(Value::Number(libm::log1p(it.num_of(&arg(a, 0))?)))
204}
205pub(crate) fn math_sum_precise(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
209 let source = arg(a, 0);
210 let items = it.iter_to_vec(&source)?;
211
212 let mut has_nan = false;
213 let mut has_pos_inf = false;
214 let mut has_neg_inf = false;
215
216 let mut numbers = alloc::vec::Vec::with_capacity(items.len());
217 for item in items {
218 let n = item.to_number();
219 if n.is_nan() {
220 has_nan = true;
221 } else if n == f64::INFINITY {
222 has_pos_inf = true;
223 } else if n == f64::NEG_INFINITY {
224 has_neg_inf = true;
225 } else {
226 numbers.push(n);
227 }
228 }
229
230 if has_nan || (has_pos_inf && has_neg_inf) {
231 return Ok(Value::Number(f64::NAN));
232 }
233 if has_pos_inf {
234 return Ok(Value::Number(f64::INFINITY));
235 }
236 if has_neg_inf {
237 return Ok(Value::Number(f64::NEG_INFINITY));
238 }
239
240 let mut sum = 0.0f64;
242 let mut c = 0.0f64;
243 for x in numbers {
244 let t = sum + x;
245 if libm::fabs(sum) >= libm::fabs(x) {
246 c += (sum - t) + x;
247 } else {
248 c += (x - t) + sum;
249 }
250 sum = t;
251 }
252 Ok(Value::Number(sum + c))
253}
254
255pub(crate) fn object_get_prototype_of(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
259 let v = arg(a, 0);
260 if matches!(v, Value::Undefined | Value::Null) {
261 return Err(it.type_error("Cannot convert undefined or null to object"));
262 }
263 let obj = match v {
264 Value::Object(o) => o,
265 other => match super::object_array::object_ctor(it, Value::Undefined, &[other])? {
266 Value::Object(o) => o,
267 _ => return Ok(Value::Null),
268 },
269 };
270 if matches!(obj.borrow().kind, ObjKind::Proxy(_)) {
271 return super::collections::pm_get_prototype_of(it, &obj);
272 }
273 Ok(effective_proto(it, &obj))
274}
275
276pub(crate) fn effective_proto(it: &Interp, o: &Rc<RefCell<Obj>>) -> Value {
284 match implicit_proto(it, o) {
285 Some(p) => Value::Object(p),
286 None => Value::Null,
287 }
288}
289
290pub(crate) fn global_proto_obj(global: &Rc<RefCell<Scope>>, name: &str) -> Option<Rc<RefCell<Obj>>> {
292 match global.borrow().vars.get(name) {
293 Some(Value::Object(c)) => match c.borrow().props.get("prototype") {
294 Some(Value::Object(p)) => Some(p.clone()),
295 _ => None,
296 },
297 _ => None,
298 }
299}
300
301pub(crate) fn global_ctor_proto(it: &Interp, name: &str) -> Option<Rc<RefCell<Obj>>> {
303 match it.global.borrow().vars.get(name) {
304 Some(Value::Object(c)) => match c.borrow().props.get("prototype") {
305 Some(Value::Object(p)) => Some(p.clone()),
306 _ => None,
307 },
308 _ => None,
309 }
310}
311
312pub(crate) fn implicit_proto(it: &Interp, o: &Rc<RefCell<Obj>>) -> Option<Rc<RefCell<Obj>>> {
318 let (explicit, null_proto, ctor_name) = {
319 let b = o.borrow();
320 let name = match &b.kind {
321 ObjKind::Array(_) => Some("Array"),
322 ObjKind::PromiseObj(_) => Some("Promise"),
323 ObjKind::MapObj(_) => Some("Map"),
324 ObjKind::SetObj(_) => Some("Set"),
325 ObjKind::RegExpObj(_) => Some("RegExp"),
326 ObjKind::DateObj(_) => Some("Date"),
327 ObjKind::Iter => return super::iter_helpers::array_iterator_proto(it),
328 ObjKind::Generator(gs) => {
329 let is_async = gs.borrow().func.is_async();
330 return if is_async {
331 super::iter_helpers::async_generator_proto(it)
332 } else {
333 super::iter_helpers::generator_proto(it)
334 };
335 }
336 _ if b.is_callable() => Some(b.function_class_name()),
337 _ if b.props.contains_key("_dv_bytes") => Some("DataView"),
338 _ => None,
339 };
340 (b.proto.clone(), b.is_null_proto(), name)
341 };
342 if explicit.is_some() {
343 return explicit;
344 }
345 if null_proto {
346 return None;
347 }
348 if ctor_name.is_none() {
349 if let Some(Value::Object(ctor)) = o.borrow().props.get("constructor").cloned() {
350 if let ObjKind::Function(fd) = &ctor.borrow().kind {
351 if fd.is_generator() {
352 let is_async = fd.is_async();
353 let gp = if is_async {
354 super::iter_helpers::async_generator_proto(it)
355 } else {
356 super::iter_helpers::generator_proto(it)
357 };
358 if let Some(p) = gp {
359 if !Rc::ptr_eq(&p, o) {
360 return Some(p);
361 }
362 }
363 }
364 }
365 }
366 }
367 if let Some(Some(p)) = it.host_proto_of(&o.borrow().kind) {
369 return Some(p);
370 }
371 let object_proto = global_ctor_proto(it, "Object")?;
372 if Rc::ptr_eq(&object_proto, o) {
373 return None;
374 }
375 match ctor_name.and_then(|n| global_ctor_proto(it, n)) {
376 Some(p) if !Rc::ptr_eq(&p, o) => Some(p),
377 _ => Some(object_proto),
378 }
379}
380pub(crate) fn object_set_prototype_of(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
382 let target = arg(a, 0);
383 if matches!(target, Value::Undefined | Value::Null) {
384 return Err(it.type_error("Object.setPrototypeOf called on null or undefined"));
385 }
386 let proto_arg = arg(a, 1);
387 if !matches!(proto_arg, Value::Object(_) | Value::Null) {
388 return Err(it.type_error("Object prototype may only be an Object or null"));
389 }
390 if let Value::Object(o) = &target {
391 if !ordinary_or_proxy_set_prototype_of(it, o, &proto_arg)? {
392 return Err(it.type_error("#<Object> is not extensible"));
393 }
394 }
395 Ok(target)
396}
397
398pub(crate) fn ordinary_or_proxy_set_prototype_of(it: &mut Interp, o: &super::super::value::ObjRef, proto_arg: &Value) -> Result<bool, Value> {
400 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
401 return super::collections::pm_set_prototype_of(it, o, proto_arg);
402 }
403 ordinary_set_prototype_of(it, o, proto_arg)
404}
405
406pub(crate) fn ordinary_set_prototype_of(it: &mut Interp, o: &super::super::value::ObjRef, proto_arg: &Value) -> Result<bool, Value> {
407 let host_ref = o.borrow().kind.host_ref();
409 if let (Some(h), Value::Object(p)) = (host_ref, proto_arg) {
410 if (it.host.set_proto)(it, h, p) {
411 return Ok(true);
412 }
413 }
414 let same = match (effective_proto(it, o), proto_arg) {
415 (Value::Object(cur), Value::Object(p)) => Rc::ptr_eq(&cur, p),
416 (Value::Null, Value::Null) => true,
417 _ => false,
418 };
419 if same {
420 return Ok(true);
421 }
422 if global_ctor_proto(it, "Object").is_some_and(|op| Rc::ptr_eq(&op, o)) {
424 return Ok(false);
425 }
426 let locked = {
428 let b = o.borrow();
429 b.is_frozen() || b.is_sealed() || b.is_non_extensible()
430 };
431 if locked {
432 return Ok(false);
433 }
434 if let Value::Object(p) = proto_arg {
436 let mut cur = Some(p.clone());
437 let mut guard = 0u32;
438 while let Some(c) = cur {
439 if Rc::ptr_eq(&c, o) {
440 return Ok(false);
441 }
442 guard += 1;
443 if guard > 10000 {
444 break;
445 }
446 let b = c.borrow();
447 if matches!(b.kind, ObjKind::Proxy(_)) {
448 break;
449 }
450 cur = b.proto.clone();
451 }
452 }
453 match proto_arg {
454 Value::Object(p) => {
455 let mut b = o.borrow_mut();
456 b.proto = Some(p.clone());
457 b.set_null_proto(false);
458 }
459 Value::Null => {
460 let mut b = o.borrow_mut();
461 b.proto = None;
462 b.set_null_proto(true);
465 }
466 _ => {}
467 }
468 Ok(true)
469}
470pub(crate) fn object_from_entries(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
471 let iterable = arg(a, 0);
472 if matches!(iterable, Value::Undefined | Value::Null) {
473 return Err(it.type_error("Object.fromEntries requires an iterable"));
474 }
475 let o = Obj::plain();
476 if let Some((iterator, next_fn)) = it.open_lazy_iterator(&iterable)? {
477 while let Some(entry) = it.iter_step_once(&next_fn, &iterator)? {
478 if let Err(e) = from_entries_add(it, &o, &entry) {
479 let _ = it.iterator_close(&iterator);
480 return Err(e);
481 }
482 }
483 } else {
484 for entry in it.iter_to_vec(&iterable)? {
485 from_entries_add(it, &o, &entry)?;
486 }
487 }
488 Ok(Value::Object(o))
489}
490
491fn from_entries_add(it: &mut Interp, target: &super::super::value::ObjRef, entry: &Value) -> Result<(), Value> {
493 if !matches!(entry, Value::Object(_)) {
494 return Err(it.type_error("Iterator value is not an entry object"));
495 }
496 let k = it.get_property(entry, "0")?;
497 let v = it.get_property(entry, "1")?;
498 let key = match &k {
499 Value::Str(_) => k.to_js_string(),
500 _ => it.to_string_value(k)?,
501 };
502 target.borrow_mut().props.insert(key.into(), v);
503 Ok(())
504}
505pub(crate) fn object_freeze(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
509 let v = arg(a, 0);
510 if let Value::Object(o) = &v {
511 if matches!(o.borrow().kind, ObjKind::Proxy(_)) && !super::collections::pm_prevent_extensions(it, o)? {
512 return Err(it.type_error("'preventExtensions' on proxy: trap returned falsish"));
513 }
514 o.borrow_mut().set_frozen(true);
515 }
516 Ok(v)
517}
518pub(crate) fn object_is_frozen(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
520 Ok(Value::Bool(match arg(a, 0) {
521 Value::Object(o) => o.borrow().is_frozen(),
522 _ => true,
523 }))
524}
525pub(crate) fn object_seal(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
528 let v = arg(a, 0);
529 if let Value::Object(o) = &v {
530 if matches!(o.borrow().kind, ObjKind::Proxy(_)) && !super::collections::pm_prevent_extensions(it, o)? {
531 return Err(it.type_error("'preventExtensions' on proxy: trap returned falsish"));
532 }
533 o.borrow_mut().set_sealed(true);
534 }
535 Ok(v)
536}
537pub(crate) fn object_is_sealed(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
538 Ok(Value::Bool(match arg(a, 0) {
539 Value::Object(o) => {
540 let b = o.borrow();
541 b.is_frozen() || b.is_sealed()
542 }
543 _ => true,
544 }))
545}
546pub(crate) fn object_prevent_extensions(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
548 let v = arg(a, 0);
549 if let Value::Object(o) = &v {
550 if !super::collections::pm_prevent_extensions(it, o)? {
551 return Err(it.type_error("'preventExtensions' on proxy: trap returned falsish"));
552 }
553 }
554 Ok(v)
555}
556pub(crate) fn object_is_extensible(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
557 Ok(Value::Bool(match arg(a, 0) {
558 Value::Object(o) => super::collections::pm_is_extensible(it, &o)?,
559 _ => false,
560 }))
561}
562pub(crate) fn object_is(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
566 let x = arg(a, 0);
567 let y = arg(a, 1);
568 let result = match (&x, &y) {
569 (Value::Number(nx), Value::Number(ny)) => {
570 if nx.is_nan() && ny.is_nan() {
571 true
572 } else if *nx == 0.0 && *ny == 0.0 {
573 nx.is_sign_positive() == ny.is_sign_positive()
574 } else {
575 nx == ny
576 }
577 }
578 _ => x.strict_eq(&y),
579 };
580 Ok(Value::Bool(result))
581}
582pub(crate) fn object_create(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
583 let obj = Obj::plain();
585 match arg(a, 0) {
589 Value::Object(p) => obj.borrow_mut().proto = Some(p),
590 Value::Null => obj.borrow_mut().set_null_proto(true),
591 _ => return Err(it.type_error("Object prototype may only be an Object or null")),
592 }
593 let props = arg(a, 1);
597 if !matches!(props, Value::Undefined) {
598 define_properties_from(it, &Value::Object(obj.clone()), &props)?;
599 }
600 Ok(Value::Object(obj))
601}
602
603fn validate_array_length(it: &mut Interp, v: Value) -> Result<usize, Value> {
607 let pv = if matches!(v, Value::Object(_)) {
608 it.to_primitive(v, "number")?
609 } else {
610 v
611 };
612 if matches!(&pv, Value::BigInt(_)) {
613 return Err(it.type_error("Cannot convert a BigInt value to a number"));
614 }
615 if matches!(&pv, Value::Str(s) if s.len() > 8 && s.starts_with("Symbol(") && s.ends_with(')')) {
616 return Err(it.type_error("Cannot convert a Symbol value to a number"));
617 }
618 let n = pv.to_number();
619 if !n.is_finite() || n < 0.0 || n > (u32::MAX as f64) || libm::trunc(n) != n {
620 return Err(it.range_error("Invalid array length"));
621 }
622 let len = n as usize;
623 if len > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
624 return Err(it.range_error("Array length exceeds maximum dense array limit"));
625 }
626 Ok(len)
627}
628
629pub(crate) fn apply_define_property(it: &mut Interp, obj: &Value, key: &str, desc: &Value) -> Result<(), Value> {
630 let Value::Object(o) = obj else { return Ok(()) };
631 let o = unwrap_proxy_target(o);
632
633 let writable = obj_prop(desc, "writable").map(|v| v.truthy());
634 let configurable = obj_prop(desc, "configurable").map(|v| v.truthy());
635 let enumerable = obj_prop(desc, "enumerable").map(|v| v.truthy());
636
637 let is_bytes_numeric = matches!(&o.borrow().kind, ObjKind::Bytes(_))
638 && crate::os_lib::ecma::value::is_canonical_numeric_key(key);
639 if is_bytes_numeric {
640 if let Some(v) = obj_prop(desc, "value") {
641 it.set_property(obj, key, v);
642 }
643 return Ok(());
644 }
645 let is_array = matches!(&o.borrow().kind, ObjKind::Array(_));
646 if is_array {
647 if key == "length" {
648 if let Some(v) = obj_prop(desc, "value") {
649 let new_len = validate_array_length(it, v)?;
650 let mut b = o.borrow_mut();
651 let cur_len = match &b.kind {
652 ObjKind::Array(items) => items.len(),
653 _ => 0,
654 };
655 if new_len < cur_len {
656 if let ObjKind::Array(items) = &mut b.kind {
657 items.truncate(new_len);
658 }
659 if let Some(mut mask) = b.holes().map(<[bool]>::to_vec) {
660 mask.truncate(new_len);
661 b.set_holes(if mask.iter().any(|&h| h) {
662 Some(alloc::boxed::Box::new(mask))
663 } else {
664 None
665 });
666 }
667 } else if new_len > cur_len && !b.grow_array(new_len) {
668 return Err(it.range_error("Invalid array length"));
669 }
670 }
671 if writable == Some(false) {
673 o.borrow_mut().insert_attr(
674 String::from("length"),
675 super::super::value::PropertyAttributes { writable: false, configurable: false, enumerable: false },
676 );
677 }
678 return Ok(());
679 }
680 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
681 if idx >= crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
682 return Err(it.range_error("Array index exceeds maximum dense array limit"));
683 }
684 let get = obj_prop(desc, "get");
685 let set = obj_prop(desc, "set");
686 let is_accessor = get.is_some() || set.is_some();
687 let existed = {
688 let b = o.borrow();
689 matches!(&b.kind, ObjKind::Array(items) if idx < items.len() && !b.is_hole(idx))
690 || b.has_accessor(key)
691 };
692 {
693 let mut b = o.borrow_mut();
694 let cur_len = match &b.kind {
695 ObjKind::Array(items) => items.len(),
696 _ => 0,
697 };
698 if idx >= cur_len && !b.grow_array(idx + 1) {
699 return Err(it.range_error("Invalid array length"));
700 }
701 if is_accessor {
702 use super::super::value::Accessor;
703 let (prev_get, prev_set) = b
704 .get_accessor(key)
705 .map(|a| (a.get.clone(), a.set.clone()))
706 .unwrap_or_default();
707 let callable = |v: &Value| matches!(v, Value::Object(f) if f.borrow().is_callable());
708 let getter = if get.is_some() { get.filter(callable) } else { prev_get };
709 let setter = if set.is_some() { set.filter(callable) } else { prev_set };
710 b.insert_accessor(
711 String::from(key),
712 Accessor { get: getter, set: setter },
713 );
714 b.clear_hole(idx);
715 } else if let Some(v) = obj_prop(desc, "value") {
716 if let ObjKind::Array(items) = &mut b.kind {
717 items[idx] = v;
718 }
719 b.remove_accessor(key);
720 b.clear_hole(idx);
721 } else if !existed {
722 b.clear_hole(idx);
723 }
724 }
725 if writable.is_some() || configurable.is_some() || enumerable.is_some() || !existed {
727 let prev = if existed {
728 o.borrow().get_attr_or_default(key)
729 } else {
730 super::super::value::PropertyAttributes { writable: false, configurable: false, enumerable: false }
731 };
732 o.borrow_mut().insert_attr(
733 String::from(key),
734 super::super::value::PropertyAttributes {
735 writable: writable.unwrap_or(prev.writable),
736 configurable: configurable.unwrap_or(prev.configurable),
737 enumerable: enumerable.unwrap_or(prev.enumerable),
738 },
739 );
740 }
741 return Ok(());
742 }
743 }
744 let get = obj_prop(desc, "get");
745 let set = obj_prop(desc, "set");
746 let has_value = obj_prop(desc, "value").is_some();
747
748 let host_ref = o.borrow().kind.host_ref();
750 if let Some(h) = host_ref {
751 if (it.host.define)(it, h, key, get.clone(), set.clone(), obj_prop(desc, "value")) {
752 return Ok(());
753 }
754 }
755
756 let virtual_fn_val = virtual_fn_prop_value(&o.borrow(), key);
757 let is_new = !o.borrow().props.contains_key(key)
758 && !o.borrow().has_accessor(key)
759 && virtual_fn_val.is_none();
760 let attr = if is_new {
761 super::super::value::PropertyAttributes {
762 writable: writable.unwrap_or(false),
763 configurable: configurable.unwrap_or(false),
764 enumerable: enumerable.unwrap_or(false),
765 }
766 } else {
767 let prev = o.borrow().get_attr_or_default(key);
768 super::super::value::PropertyAttributes {
769 writable: writable.unwrap_or(prev.writable),
770 configurable: configurable.unwrap_or(prev.configurable),
771 enumerable: enumerable.unwrap_or(prev.enumerable),
772 }
773 };
774
775 if get.is_some() || set.is_some() {
776 use super::super::value::Accessor;
781 let (prev_get, prev_set) = o
782 .borrow()
783 .get_accessor(key)
784 .map(|a| (a.get.clone(), a.set.clone()))
785 .unwrap_or_default();
786 let callable = |v: &Value| matches!(v, Value::Object(f) if f.borrow().is_callable());
787 let getter = if get.is_some() { get.filter(callable) } else { prev_get };
788 let setter = if set.is_some() { set.filter(callable) } else { prev_set };
789 o.borrow_mut().insert_accessor(
790 alloc::string::String::from(key),
791 Accessor { get: getter, set: setter },
792 );
793 o.borrow_mut().props.shift_remove(key);
794 } else if has_value {
795 let val = obj_prop(desc, "value").unwrap_or(Value::Undefined);
797 o.borrow_mut().props.insert(alloc::string::String::from(key).into(), val);
798 o.borrow_mut().remove_accessor(key);
799 } else if is_new || (writable.is_some() && o.borrow().has_accessor(key)) {
800 o.borrow_mut().remove_accessor(key);
802 o.borrow_mut().props.insert(alloc::string::String::from(key).into(), Value::Undefined);
803 } else if let Some(v) = virtual_fn_val {
804 o.borrow_mut().props.insert(alloc::string::String::from(key).into(), v);
806 }
807
808 {
809 let mut b = o.borrow_mut();
810 b.delete_virtual_fn_prop(key);
811 b.insert_attr(alloc::string::String::from(key), attr);
812 }
813 let _ = it;
814 Ok(())
815}
816
817pub(crate) fn object_define_property(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
818 let obj = arg(a, 0);
819 let key = it.to_string_value(arg(a, 1))?;
820 let Value::Object(o) = &obj else {
823 return Err(it.type_error("Object.defineProperty called on non-object"));
824 };
825 let desc = to_property_descriptor(it, &arg(a, 2))?;
826 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
827 if !super::collections::pm_define_own_property(it, o, &key, &desc)? {
828 return Err(it.type_error(alloc::format!("'defineProperty' on proxy: trap returned falsish for property '{}'", key)));
829 }
830 return Ok(obj);
831 }
832 define_property_desc(it, &obj, &key, &desc)?;
833 Ok(obj)
834}
835
836pub(crate) fn define_property_desc(it: &mut Interp, obj: &Value, key: &str, desc: &Value) -> Result<(), Value> {
838 let Value::Object(o) = obj else {
839 return Err(it.type_error("Object.defineProperty called on non-object"));
840 };
841 let key = key.to_string();
842 let desc = desc.clone();
843 {
844 let b = o.borrow();
845 let locked = b.is_frozen() || b.is_sealed() || b.is_non_extensible();
846 if locked
847 && matches!(b.kind, ObjKind::Plain | ObjKind::Function(_))
848 && !b.props.contains_key(&key)
849 && !b.has_accessor(&key)
850 && !b.has_virtual_fn_prop(&key)
851 {
852 return Err(it.type_error(alloc::format!("Cannot define property {}, object is not extensible", key)));
853 }
854 }
855 {
857 let ro_len;
858 let cur_len;
859 let (frozen, sealed, non_ext, is_arr);
860 {
861 let b = o.borrow();
862 is_arr = matches!(b.kind, ObjKind::Array(_)) && !b.props.contains_key("_ta_kind");
863 frozen = b.is_frozen();
864 sealed = frozen || b.is_sealed();
865 non_ext = sealed || b.is_non_extensible();
866 ro_len = frozen || b.get_attr("length").is_some_and(|a| !a.writable);
867 cur_len = match &b.kind {
868 ObjKind::Array(items) => items.len(),
869 _ => 0,
870 };
871 }
872 if is_arr {
873 if key == "length" {
874 if ro_len {
875 let newv = match obj_prop(&desc, "value") {
876 Some(v) => Some(validate_array_length(it, v)?),
877 None => None,
878 };
879 let wr = obj_prop(&desc, "writable").map(|v| v.truthy());
880 if newv.is_some_and(|n| n != cur_len) || wr == Some(true) {
881 return Err(it.type_error("Cannot redefine property: length"));
882 }
883 }
884 } else if let Some(idx) = crate::os_lib::ecma::value::parse_index(&key) {
885 if idx >= cur_len && (non_ext || ro_len) {
886 return Err(it.type_error(alloc::format!("Cannot define property {}, object is not extensible", idx)));
887 }
888 if idx < cur_len {
889 let attr = o.borrow().get_attr_or_default(&key);
890 let fixed = (frozen || !attr.writable) && (sealed || !attr.configurable);
891 let newv = obj_prop(&desc, "value");
892 let changes = match (&newv, &o.borrow().kind) {
893 (Some(nv), ObjKind::Array(items)) => !items.get(idx).is_some_and(|c| c.strict_eq(nv)),
894 _ => false,
895 };
896 if fixed && changes {
897 return Err(it.type_error(alloc::format!("Cannot redefine property: {}", idx)));
898 }
899 }
900 }
901 }
902 }
903 define_own_property_checked(it, obj, &key, &desc)
904}
905
906pub(crate) fn object_define_properties(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
907 let obj = arg(a, 0);
908 if !matches!(obj, Value::Object(_)) {
909 return Err(it.type_error("Object.defineProperties called on non-object"));
910 }
911 define_properties_from(it, &obj, &arg(a, 1))?;
912 Ok(obj)
913}
914
915pub(crate) fn define_properties_from(it: &mut Interp, obj: &Value, props: &Value) -> Result<(), Value> {
918 let po = match props {
919 Value::Object(_) => props.clone(),
920 Value::Undefined | Value::Null => {
921 return Err(it.type_error("Cannot convert undefined or null to object"));
922 }
923 _ => return Ok(()),
924 };
925 let Value::Object(d) = &po else { return Ok(()) };
926 let mut keys: alloc::vec::Vec<String> = alloc::vec::Vec::new();
928 for k in super::collections::pm_own_keys(it, d)? {
929 let name = k.to_js_string();
930 let desc = super::collections::pm_get_own_property(it, d, &name)?;
931 if obj_prop(&desc, "enumerable").is_some_and(|e| e.truthy()) {
932 keys.push(name);
933 }
934 }
935 let mut list: alloc::vec::Vec<(String, Value)> = alloc::vec::Vec::new();
936 for key in keys {
937 let raw = it.get_property(&po, &key)?;
938 let desc = to_property_descriptor(it, &raw)?;
939 list.push((key, desc));
940 }
941 for (key, desc) in list {
942 define_own_property_checked(it, obj, &key, &desc)?;
943 }
944 Ok(())
945}
946
947pub(crate) fn same_value_pd(x: &Value, y: &Value) -> bool {
948 match (x, y) {
949 (Value::Number(a), Value::Number(b)) => {
950 if a.is_nan() && b.is_nan() {
951 true
952 } else if *a == 0.0 && *b == 0.0 {
953 a.is_sign_positive() == b.is_sign_positive()
954 } else {
955 a == b
956 }
957 }
958 _ => x.strict_eq(y),
959 }
960}
961
962fn desc_has_property(it: &mut Interp, o: &super::super::value::ObjRef, key: &str) -> Result<bool, Value> {
965 let mut cur = o.clone();
966 for _ in 0..1000 {
967 if matches!(cur.borrow().kind, ObjKind::Proxy(_)) {
968 return super::collections::pm_has_property(it, &cur, key);
969 }
970 if super::props_methods::has_own_property(&cur, key) {
971 return Ok(true);
972 }
973 let explicit = cur.borrow().proto.clone();
974 match explicit.or_else(|| implicit_proto(it, &cur)) {
975 Some(p) => cur = p,
976 None => break,
977 }
978 }
979 Ok(it.has_property_chain(o, key))
980}
981
982pub(crate) fn to_property_descriptor(it: &mut Interp, v: &Value) -> Result<Value, Value> {
985 let Value::Object(o) = v else {
986 return Err(it.type_error("Property description must be an object"));
987 };
988 let out = Obj::plain();
989 let mut has = [false; 6];
990 for (i, name) in ["enumerable", "configurable", "value", "writable", "get", "set"].iter().enumerate() {
991 let present = desc_has_property(it, o, name)?;
992 if !present {
993 continue;
994 }
995 has[i] = true;
996 let mut val = it.get_property(v, name)?;
997 match i {
998 0 | 1 | 3 => val = Value::Bool(val.truthy()),
999 4 | 5 => {
1000 let callable = matches!(&val, Value::Object(f) if f.borrow().is_callable());
1001 if !callable && !matches!(val, Value::Undefined) {
1002 return Err(it.type_error(alloc::format!("Object.defineProperty: {} must be a function", name)));
1003 }
1004 }
1005 _ => {}
1006 }
1007 out.borrow_mut().props.insert((*name).into(), val);
1008 }
1009 if (has[4] || has[5]) && (has[2] || has[3]) {
1010 return Err(it.type_error("Invalid property descriptor. Cannot both specify accessors and a value or writable attribute"));
1011 }
1012 Ok(Value::Object(out))
1013}
1014
1015fn define_allowed(o: &super::super::value::ObjRef, key: &str, desc: &Value) -> bool {
1018 if matches!(&o.borrow().kind, ObjKind::Bytes(_))
1019 && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
1020 {
1021 if crate::os_lib::ecma::value::ta_valid_index(&o.borrow(), key).is_none() {
1022 return false;
1023 }
1024 if obj_prop(desc, "get").is_some() || obj_prop(desc, "set").is_some() {
1025 return false;
1026 }
1027 if obj_prop(desc, "configurable").is_some_and(|v| !v.truthy())
1028 || obj_prop(desc, "enumerable").is_some_and(|v| !v.truthy())
1029 || obj_prop(desc, "writable").is_some_and(|v| !v.truthy())
1030 {
1031 return false;
1032 }
1033 return true;
1034 }
1035 let cur = make_property_descriptor(o, key);
1036 if !matches!(cur, Value::Object(_)) {
1037 let b = o.borrow();
1039 return !(b.is_frozen() || b.is_sealed() || b.is_non_extensible());
1040 }
1041 let cget = |k: &str| obj_prop(&cur, k);
1042 let dget = |k: &str| obj_prop(desc, k);
1043 let cur_conf = cget("configurable").is_some_and(|v| v.truthy());
1044 if cur_conf {
1045 return true;
1046 }
1047 if dget("configurable").is_some_and(|v| v.truthy()) {
1048 return false;
1049 }
1050 if let Some(e) = dget("enumerable") {
1051 if e.truthy() != cget("enumerable").is_some_and(|v| v.truthy()) {
1052 return false;
1053 }
1054 }
1055 let d_acc = dget("get").is_some() || dget("set").is_some();
1056 let d_data = dget("value").is_some() || dget("writable").is_some();
1057 if !d_acc && !d_data {
1058 return true;
1059 }
1060 let c_acc = cget("get").is_some() || cget("set").is_some();
1061 if c_acc != d_acc {
1062 return false;
1063 }
1064 if c_acc {
1065 for k in ["get", "set"] {
1066 if let Some(nv) = dget(k) {
1067 if !same_value_pd(&nv, &cget(k).unwrap_or(Value::Undefined)) {
1068 return false;
1069 }
1070 }
1071 }
1072 true
1073 } else {
1074 if !cget("writable").is_some_and(|v| v.truthy()) {
1075 if dget("writable").is_some_and(|v| v.truthy()) {
1076 return false;
1077 }
1078 if let Some(nv) = dget("value") {
1079 if !same_value_pd(&nv, &cget("value").unwrap_or(Value::Undefined)) {
1080 return false;
1081 }
1082 }
1083 }
1084 true
1085 }
1086}
1087
1088pub(crate) fn define_own_property_checked(it: &mut Interp, obj: &Value, key: &str, desc: &Value) -> Result<(), Value> {
1090 if let Value::Object(o) = obj {
1091 let o = unwrap_proxy_target(o);
1092 let skip = o.borrow().kind.host_ref().is_some();
1093 if key == "length" && matches!(o.borrow().kind, ObjKind::Array(_)) {
1095 if let Some(v) = obj_prop(desc, "value") {
1096 validate_array_length(it, v)?;
1097 }
1098 }
1099 if !skip && !define_allowed(&o, key, desc) {
1100 return Err(it.type_error(alloc::format!("Cannot redefine property: {}", key)));
1101 }
1102 }
1103 apply_define_property(it, obj, key, desc)
1104}
1105
1106pub(crate) fn has_own_or_virtual(o: &super::super::value::ObjRef, key: &str) -> bool {
1108 super::props_methods::has_own_property(o, key)
1109}
1110
1111pub(crate) fn make_property_descriptor(obj: &super::super::value::ObjRef, key: &str) -> Value {
1112 let obj = unwrap_proxy_target(obj);
1113 let b = obj.borrow();
1114 let mut attr = b.get_attr_or_default(key);
1115 attr.enumerable = b.is_enumerable(key);
1116 if key == "prototype" && b.get_attr(key).is_none() && matches!(b.kind, ObjKind::Native { .. } | ObjKind::Function(_)) {
1118 attr.configurable = false;
1119 attr.writable = matches!(b.kind, ObjKind::Function(_));
1120 }
1121 if b.is_frozen() {
1123 attr.configurable = false;
1124 if !b.has_accessor(key) {
1125 attr.writable = false;
1126 }
1127 } else if b.is_sealed() {
1128 attr.configurable = false;
1129 }
1130
1131 if matches!(b.kind, ObjKind::Plain) {
1133 if let Some(Value::Str(sv)) = b.primitive() {
1134 if !is_symbol_like_key(sv) {
1135 if key == "length" {
1136 return data_descriptor(Value::Number(sv.encode_utf16().count() as f64), false, false, false);
1137 }
1138 if let Some(i) = crate::os_lib::ecma::value::parse_index(key) {
1139 if let Some(u) = sv.encode_utf16().nth(i) {
1140 return data_descriptor(Value::str(String::from_utf16_lossy(&[u])), false, true, false);
1141 }
1142 }
1143 }
1144 }
1145 }
1146 if let ObjKind::Bytes(st) = &b.kind {
1147 if crate::os_lib::ecma::value::is_canonical_numeric_key(key) {
1148 if let Some(idx) = crate::os_lib::ecma::value::ta_valid_index(&b, key) {
1149 if let Some(v) = st.get_value(idx) {
1150 return data_descriptor(v, true, true, true);
1151 }
1152 }
1153 return Value::Undefined;
1154 }
1155 }
1156 if let ObjKind::Array(items) = &b.kind {
1157 if key == "length" {
1158 let desc = Obj::plain();
1159 desc.borrow_mut().props.insert("value".into(), Value::Number(items.len() as f64));
1160 let w = !b.is_frozen() && b.get_attr("length").is_none_or(|a| a.writable);
1161 desc.borrow_mut().props.insert("writable".into(), Value::Bool(w));
1162 desc.borrow_mut().props.insert("enumerable".into(), Value::Bool(false));
1163 desc.borrow_mut().props.insert("configurable".into(), Value::Bool(false));
1164 return Value::Object(desc);
1165 }
1166 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1167 if b.has_accessor(key) {
1168 } else if let Some(v) = items.get(idx).filter(|_| !b.is_hole(idx)) {
1170 let desc = Obj::plain();
1171 desc.borrow_mut().props.insert("value".into(), v.clone());
1172 let ea = b.get_attr_or_default(key);
1173 desc.borrow_mut().props.insert("writable".into(), Value::Bool(!b.is_frozen() && ea.writable));
1174 desc.borrow_mut().props.insert("enumerable".into(), Value::Bool(ea.enumerable));
1175 desc.borrow_mut().props.insert("configurable".into(), Value::Bool(!b.is_frozen() && !b.is_sealed() && ea.configurable));
1176 return Value::Object(desc);
1177 } else {
1178 return Value::Undefined;
1179 }
1180 }
1181 }
1182 if let Some(acc) = b.get_accessor(key) {
1183 let desc = Obj::plain();
1184 if let Some(g) = &acc.get {
1185 desc.borrow_mut().props.insert("get".into(), g.clone());
1186 } else {
1187 desc.borrow_mut().props.insert("get".into(), Value::Undefined);
1188 }
1189 if let Some(s) = &acc.set {
1190 desc.borrow_mut().props.insert("set".into(), s.clone());
1191 } else {
1192 desc.borrow_mut().props.insert("set".into(), Value::Undefined);
1193 }
1194 desc.borrow_mut().props.insert("enumerable".into(), Value::Bool(attr.enumerable));
1195 desc.borrow_mut().props.insert("configurable".into(), Value::Bool(attr.configurable));
1196 Value::Object(desc)
1197 } else if let Some(v) = b.props.get(key) {
1198 let desc = Obj::plain();
1199 desc.borrow_mut().props.insert("value".into(), v.clone());
1200 desc.borrow_mut().props.insert("writable".into(), Value::Bool(attr.writable));
1201 desc.borrow_mut().props.insert("enumerable".into(), Value::Bool(attr.enumerable));
1202 desc.borrow_mut().props.insert("configurable".into(), Value::Bool(attr.configurable));
1203 Value::Object(desc)
1204 } else if let Some(v) = virtual_fn_prop_value(&b, key) {
1205 data_descriptor(v, false, false, !b.is_frozen() && !b.is_sealed())
1207 } else {
1208 Value::Undefined
1209 }
1210}
1211
1212pub(crate) fn virtual_fn_prop_value(b: &Obj, key: &str) -> Option<Value> {
1214 if b.props.contains_key(key) || b.has_accessor(key) || !b.has_virtual_fn_prop(key) {
1215 return None;
1216 }
1217 match (&b.kind, key) {
1218 (ObjKind::Function(fd), "name") => Some(Value::str(fd.name())),
1219 (ObjKind::Function(fd), "length") => Some(Value::Number(
1220 fd.params()
1221 .iter()
1222 .take_while(|p| p.default.is_none() && !p.is_rest)
1223 .count() as f64,
1224 )),
1225 (ObjKind::Native { name, .. }, "name") => {
1226 Some(Value::str(crate::os_lib::ecma::fn_meta::native_name_string(name)))
1227 }
1228 (ObjKind::Native { name, .. }, "length") => {
1229 Some(Value::Number(crate::os_lib::ecma::fn_meta::native_length(name) as f64))
1230 }
1231 (ObjKind::Resolver { .. }, "name") => Some(Value::str("")),
1232 (ObjKind::Resolver { .. }, "length") => Some(Value::Number(1.0)),
1233 (ObjKind::Bound(bd), "name") => {
1234 let inner = match &bd.target {
1235 Value::Object(to) => to
1236 .try_borrow()
1237 .ok()
1238 .and_then(|tb| {
1239 if let Some(v) = tb.props.get("name") {
1240 match v {
1241 Value::Str(s) => Some((**s).clone()),
1242 _ => Some(String::new()),
1243 }
1244 } else if let Some(Value::Str(s)) = virtual_fn_prop_value(&tb, "name") {
1245 Some((*s).clone())
1246 } else {
1247 None
1248 }
1249 })
1250 .unwrap_or_default(),
1251 _ => String::new(),
1252 };
1253 Some(Value::str(alloc::format!("bound {}", inner)))
1254 }
1255 (ObjKind::Bound(bd), "length") => {
1256 let len = match &bd.target {
1257 Value::Object(to) => to
1258 .try_borrow()
1259 .ok()
1260 .map(|tb| {
1261 let v = if let Some(v) = tb.props.get("length") {
1262 Some(v.clone())
1263 } else {
1264 virtual_fn_prop_value(&tb, "length")
1265 };
1266 match v {
1267 Some(Value::Number(n)) => {
1268 if n.is_nan() || n <= 0.0 || n == f64::NEG_INFINITY {
1269 0.0
1270 } else if n == f64::INFINITY {
1271 f64::INFINITY
1272 } else {
1273 let int_n = libm::trunc(n);
1274 (int_n - (bd.bound_args.len() as f64)).max(0.0)
1275 }
1276 }
1277 _ => 0.0,
1278 }
1279 })
1280 .unwrap_or(0.0),
1281 _ => 0.0,
1282 };
1283 Some(Value::Number(len))
1284 }
1285 _ => None,
1286 }
1287}
1288
1289pub(crate) fn data_descriptor(v: Value, writable: bool, enumerable: bool, configurable: bool) -> Value {
1291 let desc = Obj::plain();
1292 {
1293 let mut d = desc.borrow_mut();
1294 d.props.insert("value".into(), v);
1295 d.props.insert("writable".into(), Value::Bool(writable));
1296 d.props.insert("enumerable".into(), Value::Bool(enumerable));
1297 d.props.insert("configurable".into(), Value::Bool(configurable));
1298 }
1299 Value::Object(desc)
1300}
1301
1302pub(crate) fn proxy_define_property_trap(
1303 it: &mut Interp,
1304 o: &super::super::value::ObjRef,
1305 key: &str,
1306 desc: &Value,
1307) -> Result<bool, Value> {
1308 if !matches!(o.borrow().kind, ObjKind::Proxy(_)) {
1309 return Ok(false);
1310 }
1311 super::collections::pm_define_own_property(it, o, key, desc)
1312}
1313
1314pub(crate) fn object_get_own_property_descriptor(
1315 it: &mut Interp,
1316 _t: Value,
1317 a: &[Value],
1318) -> Result<Value, Value> {
1319 let target_v = arg(a, 0);
1320 if matches!(target_v, Value::Undefined | Value::Null) {
1321 return Err(it.type_error("Cannot convert undefined or null to object"));
1322 }
1323 let key = it.to_string_value(arg(a, 1))?;
1324 if let Value::Str(s) = &target_v {
1326 let units: Vec<u16> = s.encode_utf16().collect();
1327 if key == "length" {
1328 return Ok(data_descriptor(Value::Number(units.len() as f64), false, false, false));
1329 }
1330 if let Some(&u) = crate::os_lib::ecma::value::parse_index(&key).and_then(|i| units.get(i)) {
1331 let ch = String::from_utf16_lossy(&[u]);
1332 return Ok(data_descriptor(Value::str(ch), false, true, false));
1333 }
1334 return Ok(Value::Undefined);
1335 }
1336 let Value::Object(o) = target_v else { return Ok(Value::Undefined) };
1337 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
1338 return super::collections::pm_get_own_property(it, &o, &key);
1339 }
1340 let host_ref = o.borrow().kind.host_ref();
1342 if let Some(h) = host_ref {
1343 match (it.host.own)(it, h, &key) {
1344 HostOwn::Generic => {}
1345 HostOwn::Absent => return Ok(Value::Undefined),
1346 HostOwn::Accessor(g, st) => {
1347 let desc = Obj::plain();
1348 let mut d = desc.borrow_mut();
1349 d.props.insert("get".into(), g.unwrap_or(Value::Undefined));
1350 d.props.insert("set".into(), st.unwrap_or(Value::Undefined));
1351 d.props.insert("enumerable".into(), Value::Bool(true));
1352 d.props.insert("configurable".into(), Value::Bool(true));
1353 drop(d);
1354 return Ok(Value::Object(desc));
1355 }
1356 HostOwn::Data(v) => {
1357 let desc = Obj::plain();
1358 let mut d = desc.borrow_mut();
1359 d.props.insert("value".into(), v);
1360 d.props.insert("writable".into(), Value::Bool(true));
1361 d.props.insert("enumerable".into(), Value::Bool(true));
1362 d.props.insert("configurable".into(), Value::Bool(true));
1363 drop(d);
1364 return Ok(Value::Object(desc));
1365 }
1366 }
1367 }
1368 if key == "prototype" {
1369 let _ = Obj::fn_prototype(&o);
1370 }
1371 Ok(make_property_descriptor(&o, &key))
1372}
1373
1374pub(crate) fn object_get_own_property_descriptors(
1375 it: &mut Interp,
1376 _t: Value,
1377 a: &[Value],
1378) -> Result<Value, Value> {
1379 let target = arg(a, 0);
1380 match &target {
1381 Value::Undefined | Value::Null => return Err(it.type_error("Cannot convert undefined or null to object")),
1382 Value::Str(s) if target.type_of() != "symbol" => {
1383 let result = Obj::plain();
1384 let n = s.encode_utf16().count();
1385 for key in (0..n).map(|i| i.to_string()).chain(core::iter::once(String::from("length"))) {
1386 let d = object_get_own_property_descriptor(it, Value::Undefined, &[target.clone(), Value::str(key.as_str())])?;
1387 result.borrow_mut().props.insert(key.into(), d);
1388 }
1389 return Ok(Value::Object(result));
1390 }
1391 _ => {}
1392 }
1393 let Value::Object(o) = target else { return Ok(Value::Object(Obj::plain())) };
1394 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
1395 let result = Obj::plain();
1396 for k in super::collections::pm_own_keys(it, &o)? {
1397 let key = k.to_js_string();
1398 let d = super::collections::pm_get_own_property(it, &o, &key)?;
1399 if !matches!(d, Value::Undefined) {
1400 result.borrow_mut().props.insert(key.into(), d);
1401 }
1402 }
1403 return Ok(Value::Object(result));
1404 }
1405 let result = Obj::plain();
1406 let keys: alloc::vec::Vec<String> = {
1407 let b = o.borrow();
1408 if let ObjKind::Bytes(_) = &b.kind {
1409 let n = crate::os_lib::ecma::value::ta_effective_len(&b).unwrap_or(0);
1410 (0..n).map(|i| i.to_string()).collect()
1411 } else if let ObjKind::Array(items) = &b.kind {
1412 let mut ks: alloc::vec::Vec<String> = (0..items.len()).map(|i| i.to_string()).collect();
1413 ks.push(String::from("length"));
1414 ks
1415 } else {
1416 let mut ks: alloc::vec::Vec<String> = alloc::vec::Vec::new();
1417 if b.has_virtual_fn_prop("length") {
1418 ks.push(String::from("length"));
1419 }
1420 if b.has_virtual_fn_prop("name") {
1421 ks.push(String::from("name"));
1422 }
1423 for k in b.props.keys() {
1424 if !ks.iter().any(|x| x == k.as_str()) {
1425 ks.push(k.to_string());
1426 }
1427 }
1428 if let Some(acc) = b.accessors() {
1429 for k in acc.keys() {
1430 if !ks.iter().any(|x| x == k.as_str()) {
1431 ks.push(k.to_string());
1432 }
1433 }
1434 }
1435 ks
1436 }
1437 };
1438 for key in keys {
1439 let desc = make_property_descriptor(&o, &key);
1440 result.borrow_mut().props.insert(key.into(), desc);
1441 }
1442 Ok(Value::Object(result))
1443}
1444
1445pub(crate) fn number_is_integer(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1447 Ok(Value::Bool(match arg(a, 0) {
1448 Value::Number(x) => x.is_finite() && libm::floor(x) == x,
1449 _ => false,
1450 }))
1451}
1452pub(crate) fn number_is_safe_integer(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1453 Ok(Value::Bool(match arg(a, 0) {
1454 Value::Number(x) => {
1455 x.is_finite() && libm::floor(x) == x && libm::fabs(x) <= 9007199254740991.0
1456 }
1457 _ => false,
1458 }))
1459}
1460pub(crate) fn number_is_finite_static(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1461 Ok(Value::Bool(
1462 matches!(arg(a, 0), Value::Number(x) if x.is_finite()),
1463 ))
1464}
1465pub(crate) fn number_is_nan_static(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1466 Ok(Value::Bool(
1467 matches!(arg(a, 0), Value::Number(x) if x.is_nan()),
1468 ))
1469}
1470