1use super::*;
4use crate::os_lib::ecma::host::HostOwn;
5
6pub(crate) fn global_parse_int(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
15 let s = it.to_string_value(arg(a, 0))?;
16 let radix = crate::os_lib::ecma::interp::to_i32(it.num_of(&arg(a, 1))?);
17 Ok(Value::Number(crate::os_lib::ecma::numfmt::parse_int(&s, radix)))
18}
19pub(crate) fn global_parse_float(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
20 let s = it.to_string_value(arg(a, 0))?;
21 Ok(Value::Number(crate::os_lib::ecma::numfmt::parse_float(&s)))
22}
23pub(crate) fn global_is_nan(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
24 Ok(Value::Bool(it.num_of(&arg(a, 0))?.is_nan()))
25}
26pub(crate) fn global_is_finite(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
27 Ok(Value::Bool(it.num_of(&arg(a, 0))?.is_finite()))
28}
29
30pub(crate) fn global_eval(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
32 let first = arg(a, 0);
33 match &first {
34 Value::Str(s) => it.eval_source(s),
35 _ => Ok(first),
36 }
37}
38
39pub(crate) fn function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
43 dynamic_function(it, a, "function")
44}
45pub(crate) fn async_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
48 dynamic_function(it, a, "async function")
49}
50pub(crate) fn generator_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
51 dynamic_function(it, a, "function*")
52}
53pub(crate) fn async_generator_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
54 dynamic_function(it, a, "async function*")
55}
56fn dynamic_function(it: &mut Interp, a: &[Value], head: &str) -> Result<Value, Value> {
57 let (params, body): (String, String) = match a.len() {
58 0 => (String::new(), String::new()),
59 1 => (String::new(), a[0].to_js_string()),
60 n => {
61 let params = a[..n - 1]
62 .iter()
63 .map(|v| v.to_js_string())
64 .collect::<Vec<_>>()
65 .join(",");
66 (params, a[n - 1].to_js_string())
67 }
68 };
69 let source = format!("({} anonymous({}\n) {{\n{}\n}})", head, params, body);
70 it.eval_source(&source)
71}
72
73pub fn string_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
77 let pair = match key {
78 "charAt" => ("charAt", str_char_at as NativeFn),
79 "charCodeAt" => ("charCodeAt", str_char_code_at as NativeFn),
80 "codePointAt" => ("codePointAt", str_code_point_at as NativeFn),
81 "localeCompare" => ("localeCompare", str_locale_compare as NativeFn),
82 "indexOf" => ("indexOf", str_index_of as NativeFn),
83 "lastIndexOf" => ("lastIndexOf", str_last_index_of as NativeFn),
84 "includes" => ("includes", str_includes as NativeFn),
85 "startsWith" => ("startsWith", str_starts_with as NativeFn),
86 "endsWith" => ("endsWith", str_ends_with as NativeFn),
87 "slice" => ("slice", str_slice as NativeFn),
88 "substring" => ("substring", str_substring as NativeFn),
89 "substr" => ("substr", str_substr as NativeFn),
90 "toUpperCase" => ("toUpperCase", str_to_upper as NativeFn),
91 "toLocaleUpperCase" => ("toLocaleUpperCase", str_to_upper as NativeFn),
93 "toLocaleLowerCase" => ("toLocaleLowerCase", str_to_lower as NativeFn),
94 "toLowerCase" => ("toLowerCase", str_to_lower as NativeFn),
95 "trim" => ("trim", str_trim as NativeFn),
96 "split" => ("split", str_split as NativeFn),
97 "replace" => ("replace", str_replace as NativeFn),
98 "replaceAll" => ("replaceAll", str_replace_all as NativeFn),
99 "match" => ("match", str_match as NativeFn),
100 "matchAll" => ("matchAll", str_match_all as NativeFn),
101 "search" => ("search", str_search as NativeFn),
102 "repeat" => ("repeat", str_repeat as NativeFn),
103 "concat" => ("concat", str_concat as NativeFn),
104 "padStart" => ("padStart", str_pad_start as NativeFn),
105 "padEnd" => ("padEnd", str_pad_end as NativeFn),
106 "at" => ("at", str_at as NativeFn),
107 "toString" => ("toString", str_identity as NativeFn),
108 "valueOf" => ("valueOf", str_identity as NativeFn),
109 "trimStart" => ("trimStart", str_trim_start as NativeFn),
110 "trimEnd" => ("trimEnd", str_trim_end as NativeFn),
111 "trimLeft" => ("trimStart", str_trim_start as NativeFn),
112 "trimRight" => ("trimEnd", str_trim_end as NativeFn),
113 "Symbol(Symbol.iterator)" => ("[Symbol.iterator]", str_iterator as NativeFn),
114 "isWellFormed" => ("isWellFormed", str_is_well_formed as NativeFn),
115 "toWellFormed" => ("toWellFormed", str_to_well_formed as NativeFn),
116 "normalize" => ("normalize", str_normalize as NativeFn),
117 "anchor" => ("anchor", str_anchor as NativeFn),
118 "big" => ("big", str_big as NativeFn),
119 "blink" => ("blink", str_blink as NativeFn),
120 "bold" => ("bold", str_bold as NativeFn),
121 "fixed" => ("fixed", str_fixed as NativeFn),
122 "fontcolor" => ("fontcolor", str_fontcolor as NativeFn),
123 "fontsize" => ("fontsize", str_fontsize as NativeFn),
124 "italics" => ("italics", str_italics as NativeFn),
125 "link" => ("link", str_link as NativeFn),
126 "small" => ("small", str_small as NativeFn),
127 "strike" => ("strike", str_strike as NativeFn),
128 "sub" => ("sub", str_sub as NativeFn),
129 "sup" => ("sup", str_sup as NativeFn),
130 _ => return None,
131 };
132 Some(pair)
133}
134
135pub fn string_get(s: &str, key: &str) -> Value {
137 if key == "length" {
138 return Value::Number(s.chars().count() as f64);
139 }
140 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
141 return match s.chars().nth(idx) {
142 Some(c) => Value::str(c.to_string()),
143 None => Value::Undefined,
144 };
145 }
146 string_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
147}
148
149pub(crate) fn html_wrap_tag(s: &str, tag: &str) -> String {
151 alloc::format!("<{0}>{1}</{0}>", tag, s)
152}
153pub(crate) fn html_wrap_attr(s: &str, tag: &str, attr: &str, value: &str) -> String {
155 let escaped = value.replace('"', """);
156 alloc::format!("<{0} {1}=\"{2}\">{3}</{0}>", tag, attr, escaped, s)
157}
158pub(crate) fn str_anchor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
159 Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "a", "name", &it.to_string_value(arg(a, 0))?)))
160}
161pub(crate) fn str_big(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
162 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "big")))
163}
164pub(crate) fn str_blink(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
165 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "blink")))
166}
167pub(crate) fn str_bold(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
168 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "b")))
169}
170pub(crate) fn str_fixed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
171 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "tt")))
172}
173pub(crate) fn str_fontcolor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
174 Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "font", "color", &it.to_string_value(arg(a, 0))?)))
175}
176pub(crate) fn str_fontsize(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
177 Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "font", "size", &it.to_string_value(arg(a, 0))?)))
178}
179pub(crate) fn str_italics(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
180 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "i")))
181}
182pub(crate) fn str_link(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
183 Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "a", "href", &it.to_string_value(arg(a, 0))?)))
184}
185pub(crate) fn str_small(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
186 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "small")))
187}
188pub(crate) fn str_strike(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
189 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "strike")))
190}
191pub(crate) fn str_sub(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
192 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "sub")))
193}
194pub(crate) fn str_sup(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
195 Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "sup")))
196}
197
198pub(crate) fn this_str_c<'a>(it: &mut Interp, this: &'a Value) -> Result<alloc::borrow::Cow<'a, str>, Value> {
200 match this {
201 Value::Str(s) => {
202 if is_symbol_like_key(s) {
203 return Err(it.type_error("Cannot convert a Symbol value to a string"));
204 }
205 Ok(alloc::borrow::Cow::Borrowed(s.as_str()))
206 }
207 Value::Undefined | Value::Null => Err(it.type_error("String.prototype method called on null or undefined")),
208 Value::Object(_) => Ok(alloc::borrow::Cow::Owned(it.to_string_value(this.clone())?)),
209 _ => Ok(alloc::borrow::Cow::Owned(this.to_js_string())),
210 }
211}
212
213pub(crate) fn to_str_strict(it: &mut Interp, v: Value) -> Result<String, Value> {
215 let prim = if matches!(v, Value::Object(_)) {
216 it.to_primitive(v, "string")?
217 } else {
218 v
219 };
220 if let Value::Str(s) = &prim {
221 if is_symbol_like_key(s) {
222 return Err(it.type_error("Cannot convert a Symbol value to a string"));
223 }
224 return Ok(s.to_string());
225 }
226 Ok(prim.to_js_string())
227}
228
229pub(crate) fn this_val(it: &mut Interp, this: &Value) -> Result<Value, Value> {
231 match this {
232 Value::Str(s) if !is_symbol_like_key(s) => Ok(this.clone()),
233 _ => Ok(Value::str(this_str_c(it, this)?.into_owned())),
234 }
235}
236
237#[allow(dead_code)]
238pub(crate) fn this_str(this: &Value) -> alloc::borrow::Cow<'_, str> {
239 match this {
241 Value::Str(s) => alloc::borrow::Cow::Borrowed(s.as_str()),
242 _ => alloc::borrow::Cow::Owned(this.to_js_string()),
243 }
244}
245
246pub(crate) enum Units<'a> {
249 Ascii(&'a str),
250 Wide(Vec<u16>),
251}
252
253impl<'a> Units<'a> {
254 pub(crate) fn of(s: &'a str) -> Self {
255 if s.is_ascii() {
256 Units::Ascii(s)
257 } else {
258 Units::Wide(s.encode_utf16().collect())
259 }
260 }
261
262 pub(crate) fn len(&self) -> usize {
263 match self {
264 Units::Ascii(s) => s.len(),
265 Units::Wide(v) => v.len(),
266 }
267 }
268
269 pub(crate) fn at(&self, i: usize) -> Option<u16> {
270 match self {
271 Units::Ascii(s) => s.as_bytes().get(i).map(|b| *b as u16),
272 Units::Wide(v) => v.get(i).copied(),
273 }
274 }
275
276 pub(crate) fn slice(&self, s: usize, e: usize) -> String {
278 match self {
279 Units::Ascii(t) => t.get(s..e).map(String::from).unwrap_or_default(),
280 Units::Wide(v) => v.get(s..e).map(String::from_utf16_lossy).unwrap_or_default(),
281 }
282 }
283}
284
285type UnitsCacheEntry = (Rc<String>, Option<Rc<[u16]>>);
290
291#[derive(Default)]
292pub struct UnitsCache {
293 entries: Vec<UnitsCacheEntry>,
294}
295
296const UNITS_CACHE_MIN: usize = 256;
298
299pub(crate) enum CUnits<'a> {
301 Plain(Units<'a>),
302 Ascii(Rc<String>),
303 Wide(Rc<[u16]>),
304}
305
306impl CUnits<'_> {
307 pub(crate) fn len(&self) -> usize {
308 match self {
309 CUnits::Plain(u) => u.len(),
310 CUnits::Ascii(s) => s.len(),
311 CUnits::Wide(v) => v.len(),
312 }
313 }
314 pub(crate) fn at(&self, i: usize) -> Option<u16> {
315 match self {
316 CUnits::Plain(u) => u.at(i),
317 CUnits::Ascii(s) => s.as_bytes().get(i).map(|b| *b as u16),
318 CUnits::Wide(v) => v.get(i).copied(),
319 }
320 }
321 pub(crate) fn slice(&self, s: usize, e: usize) -> String {
322 match self {
323 CUnits::Plain(u) => u.slice(s, e),
324 CUnits::Ascii(t) => t.get(s..e).map(String::from).unwrap_or_default(),
325 CUnits::Wide(v) => v.get(s..e).map(String::from_utf16_lossy).unwrap_or_default(),
326 }
327 }
328}
329
330pub(crate) fn cached_units<'a>(it: &Interp, v: &'a Value) -> CUnits<'a> {
332 let Value::Str(rc) = v else {
333 return CUnits::Plain(Units::Wide(v.to_js_string().encode_utf16().collect()));
334 };
335 if rc.len() < UNITS_CACHE_MIN {
336 return CUnits::Plain(Units::of(rc.as_str()));
337 }
338 let Ok(mut cache) = it.units_cache.try_borrow_mut() else {
339 return CUnits::Plain(Units::of(rc.as_str()));
340 };
341 if let Some(pos) = cache.entries.iter().position(|(s, _)| Rc::ptr_eq(s, rc)) {
342 let e = cache.entries.remove(pos);
343 let out = match &e.1 {
344 Some(w) => CUnits::Wide(w.clone()),
345 None => CUnits::Ascii(e.0.clone()),
346 };
347 cache.entries.push(e);
348 return out;
349 }
350 let wide: Option<Rc<[u16]>> = if rc.is_ascii() { None } else { Some(rc.encode_utf16().collect::<Vec<u16>>().into()) };
351 if cache.entries.len() >= 4 {
352 cache.entries.remove(0);
353 }
354 cache.entries.push((rc.clone(), wide.clone()));
355 match wide {
356 Some(w) => CUnits::Wide(w),
357 None => CUnits::Ascii(rc.clone()),
358 }
359}
360
361pub(crate) fn unit_len(s: &str) -> usize {
368 if s.is_ascii() {
369 s.len()
370 } else {
371 let mut units = 0;
372 for &b in s.as_bytes() {
373 if (b & 0xC0) != 0x80 {
374 units += 1;
375 if b >= 0xF0 {
376 units += 1;
377 }
378 }
379 }
380 units
381 }
382}
383pub(crate) fn str_char_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
384 let t = this_val(it, &t)?;
385 let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
386 let u = cached_units(it, &t);
387 if pos < 0.0 || pos >= (u.len() as f64) {
388 return Ok(Value::str(String::new()));
389 }
390 Ok(it.char_unit_val(u.at(pos as usize)))
391}
392pub(crate) fn str_char_code_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
393 let t = this_val(it, &t)?;
394 let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
395 let u = cached_units(it, &t);
396 if pos < 0.0 || pos >= (u.len() as f64) {
397 return Ok(Value::Number(f64::NAN));
398 }
399 match u.at(pos as usize) {
400 Some(c) => Ok(Value::Number(c as f64)),
401 None => Ok(Value::Number(f64::NAN)),
402 }
403}
404pub(crate) fn str_code_point_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
406 let t = this_val(it, &t)?;
407 let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
408 let u = cached_units(it, &t);
409 if pos < 0.0 || pos >= (u.len() as f64) {
410 return Ok(Value::Undefined);
411 }
412 let i = pos as usize;
413 let Some(hi) = u.at(i) else { return Ok(Value::Undefined) };
414 if (0xD800..0xDC00).contains(&hi) {
415 if let Some(lo) = u.at(i + 1).filter(|l| (0xDC00..0xE000).contains(l)) {
416 let cp = 0x10000 + (((hi as u32) - 0xD800) << 10) + ((lo as u32) - 0xDC00);
417 return Ok(Value::Number(cp as f64));
418 }
419 }
420 Ok(Value::Number(hi as f64))
421}pub(crate) fn str_locale_compare(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
424 let s = this_str_c(it, &t)?;
425 let other = it.to_string_value(arg(a, 0))?;
426 let locale = super::intl::ctor_locale(it, &arg(a, 1))?;
427 let _options = super::intl::get_options_object(it, &arg(a, 2), false)?;
428 let phonebook = locale.contains("-u-co-phonebk");
429 use core::cmp::Ordering;
430 Ok(Value::Number(match crate::os_lib::ecma::collate::locale_compare_with_options(&s, other.as_str(), phonebook) {
431 Ordering::Less => -1.0,
432 Ordering::Equal => 0.0,
433 Ordering::Greater => 1.0,
434 }))
435}
436fn unit_to_byte(s: &str, n: usize) -> usize {
438 if s.is_ascii() {
439 return n.min(s.len());
440 }
441 let mut u = 0;
442 for (b, c) in s.char_indices() {
443 if u >= n {
444 return b;
445 }
446 u += c.len_utf16();
447 }
448 s.len()
449}
450
451fn pos_arg_checked(it: &mut Interp, v: &Value, default: usize, len: usize) -> Result<usize, Value> {
453 if matches!(v, Value::Undefined) {
454 return Ok(default);
455 }
456 let p = it.num_of(v)?;
457 Ok(if p.is_nan() {
458 default
459 } else if p <= 0.0 {
460 0
461 } else if p.is_finite() {
462 (p as usize).min(len)
463 } else {
464 len
465 })
466}
467
468#[allow(dead_code)]
470fn pos_arg(v: &Value, default: usize, len: usize) -> usize {
471 if matches!(v, Value::Undefined) {
472 return default;
473 }
474 let p = v.to_number();
475 if p.is_nan() {
476 default
477 } else if p <= 0.0 {
478 0
479 } else if p.is_finite() {
480 (p as usize).min(len)
481 } else {
482 len
483 }
484}
485
486pub(crate) fn str_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
489 let s = this_str_c(it, &t)?.into_owned();
490 let needle = to_str_strict(it, arg(a, 0))?;
491 let start_unit = pos_arg_checked(it, &arg(a, 1), 0, unit_len(&s))?;
492 let start = unit_to_byte(&s, start_unit);
493 match s.get(start..).and_then(|rest| rest.find(&needle)) {
494 Some(off) => Ok(Value::Number(unit_len(s.get(..start + off).unwrap_or("")) as f64)),
495 None => Ok(Value::Number(-1.0)),
496 }
497}
498pub(crate) fn str_last_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
502 let s = this_str_c(it, &t)?.into_owned();
503 let needle = to_str_strict(it, arg(a, 0))?;
504 let len = unit_len(&s);
505 let nlen = unit_len(&needle);
506 let pos_num = if matches!(arg(a, 1), Value::Undefined) {
507 f64::NAN
508 } else {
509 it.num_of(&arg(a, 1))?
510 };
511 if nlen > len {
512 return Ok(Value::Number(-1.0));
513 }
514 let start_unit = if pos_num.is_nan() {
515 len - nlen
516 } else {
517 let pos = to_integer_or_infinity(pos_num);
518 if pos <= 0.0 {
519 0
520 } else if pos.is_finite() {
521 (pos as usize).min(len - nlen)
522 } else {
523 len - nlen
524 }
525 };
526 let end = unit_to_byte(&s, start_unit + nlen);
527 match s.get(..end).and_then(|head| head.rfind(&needle)) {
528 Some(b) => Ok(Value::Number(unit_len(s.get(..b).unwrap_or("")) as f64)),
529 None => Ok(Value::Number(-1.0)),
530 }
531}
532pub(crate) fn reject_regexp_arg(it: &mut Interp, v: &Value, method: &str) -> Result<(), Value> {
535 if super::regexp_proto::is_regexp(it, v)? {
536 return Err(it.type_error(alloc::format!(
537 "First argument to String.prototype.{} must not be a regular expression",
538 method
539 )));
540 }
541 Ok(())
542}
543fn clamp_unit_pos(num: f64, len: usize) -> usize {
544 let pos = to_integer_or_infinity(num);
545 if pos <= 0.0 {
546 0
547 } else if pos.is_finite() {
548 (pos as usize).min(len)
549 } else {
550 len
551 }
552}
553pub(crate) fn str_includes(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
554 let s = this_str_c(it, &t)?.into_owned();
555 let search = arg(a, 0);
556 reject_regexp_arg(it, &search, "includes")?;
557 let needle = to_str_strict(it, search)?;
558 let len = unit_len(&s);
559 let start = if matches!(arg(a, 1), Value::Undefined) {
560 0
561 } else {
562 clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
563 };
564 let start_byte = unit_to_byte(&s, start);
565 Ok(Value::Bool(s.get(start_byte..).is_some_and(|rest| rest.contains(&needle))))
566}
567pub(crate) fn str_starts_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
568 let s = this_str_c(it, &t)?.into_owned();
569 let search = arg(a, 0);
570 reject_regexp_arg(it, &search, "startsWith")?;
571 let needle = to_str_strict(it, search)?;
572 let len = unit_len(&s);
573 let start = if matches!(arg(a, 1), Value::Undefined) {
574 0
575 } else {
576 clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
577 };
578 let start_byte = unit_to_byte(&s, start);
579 Ok(Value::Bool(s.get(start_byte..).is_some_and(|rest| rest.starts_with(&needle))))
580}
581pub(crate) fn str_ends_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
582 let s = this_str_c(it, &t)?.into_owned();
583 let search = arg(a, 0);
584 reject_regexp_arg(it, &search, "endsWith")?;
585 let needle = to_str_strict(it, search)?;
586 let len = unit_len(&s);
587 let end = if matches!(arg(a, 1), Value::Undefined) {
588 len
589 } else {
590 clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
591 };
592 let end_byte = unit_to_byte(&s, end);
593 Ok(Value::Bool(s.get(..end_byte).is_some_and(|head| head.ends_with(&needle))))
594}
595pub(crate) fn str_slice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
596 let t = this_val(it, &t)?;
597 let u = cached_units(it, &t);
598 let len = u.len() as i64;
599 let start = norm_index(it.num_of(&arg(a, 0))?, len, 0);
600 let end = if matches!(arg(a, 1), Value::Undefined) {
601 len
602 } else {
603 norm_index(it.num_of(&arg(a, 1))?, len, len)
604 };
605 let (s, e) = (start.max(0) as usize, end.max(0) as usize);
606 Ok(Value::str(if s < e { u.slice(s, e.min(u.len())) } else { String::new() }))
607}pub(crate) fn str_substring(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
608 let t = this_val(it, &t)?;
609 let u = cached_units(it, &t);
610 let len = u.len();
611 let mut s = clamp_idx(it.num_of(&arg(a, 0))?, len);
612 let mut e = if matches!(arg(a, 1), Value::Undefined) {
613 len
614 } else {
615 clamp_idx(it.num_of(&arg(a, 1))?, len)
616 };
617 if s > e {
618 core::mem::swap(&mut s, &mut e);
619 }
620 Ok(Value::str(u.slice(s, e)))
621}pub(crate) fn str_substr(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
625 let t = this_val(it, &t)?;
626 let u = cached_units(it, &t);
627 let len = u.len() as i64;
628 let raw_start = it.num_of(&arg(a, 0))?;
629 let start = if raw_start < 0.0 {
630 (len + raw_start as i64).max(0)
631 } else {
632 (raw_start as i64).min(len)
633 };
634 let length = if matches!(arg(a, 1), Value::Undefined) {
635 len - start
636 } else {
637 (it.num_of(&arg(a, 1))? as i64).max(0)
638 };
639 let end = (start + length).min(len);
640 let s = start as usize;
641 let e = (end.max(start)) as usize;
642 Ok(Value::str(if s < e { u.slice(s, e) } else { String::new() }))
643}pub(crate) fn str_to_upper(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
644 Ok(Value::str(this_str_c(it, &t)?.to_uppercase()))
645}
646pub(crate) fn str_to_lower(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
647 Ok(Value::str(this_str_c(it, &t)?.to_lowercase()))
648}
649#[inline]
650fn is_ecma_ws(c: char) -> bool {
651 matches!(
652 c,
653 '\u{0009}'
654 | '\u{000A}'
655 | '\u{000B}'
656 | '\u{000C}'
657 | '\u{000D}'
658 | ' '
659 | '\u{00A0}'
660 | '\u{2028}'
661 | '\u{2029}'
662 | '\u{FEFF}'
663 ) || (c != '\u{180E}' && c.is_whitespace())
664}
665pub(crate) fn str_trim(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
666 Ok(Value::str(this_str_c(it, &t)?.trim_matches(is_ecma_ws).to_string()))
667}
668pub(crate) fn str_trim_start(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
669 Ok(Value::str(this_str_c(it, &t)?.trim_start_matches(is_ecma_ws).to_string()))
670}
671pub(crate) fn str_trim_end(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
672 Ok(Value::str(this_str_c(it, &t)?.trim_end_matches(is_ecma_ws).to_string()))
673}
674pub(crate) fn str_identity(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
675 match &t {
677 Value::Str(s) if !is_symbol_like_key(s) => return Ok(t),
678 Value::Object(o) => {
679 if let Some(p @ Value::Str(_)) = o.borrow().primitive() {
680 return Ok(p.clone());
681 }
682 }
683 _ => {}
684 }
685 Err(it.type_error("String.prototype.toString requires that 'this' be a String"))
686}
687pub(crate) fn this_number(it: &mut Interp, t: &Value, what: &str) -> Result<f64, Value> {
689 match t {
690 Value::Number(n) => Ok(*n),
691 Value::Object(o) => {
692 if let Some(Value::Number(n)) = o.borrow().primitive() {
693 return Ok(*n);
694 }
695 Err(it.type_error(alloc::format!("Number.prototype.{} requires that 'this' be a Number", what)))
696 }
697 _ => Err(it.type_error(alloc::format!("Number.prototype.{} requires that 'this' be a Number", what))),
698 }
699}
700fn this_boolean(it: &mut Interp, t: &Value, what: &str) -> Result<bool, Value> {
702 match t {
703 Value::Bool(b) => Ok(*b),
704 Value::Object(o) => {
705 if let Some(Value::Bool(b)) = o.borrow().primitive() {
706 return Ok(*b);
707 }
708 Err(it.type_error(alloc::format!("Boolean.prototype.{} requires that 'this' be a Boolean", what)))
709 }
710 _ => Err(it.type_error(alloc::format!("Boolean.prototype.{} requires that 'this' be a Boolean", what))),
711 }
712}
713pub(crate) fn str_iterator(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
720 let s = this_str_c(it, &t)?;
721 let items: Vec<Value> = s.chars().map(|c| Value::str(c.to_string())).collect();
722 Ok(Value::Object(make_iterator(items)))
723}
724pub(crate) fn str_is_well_formed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
727 this_str_c(it, &t)?;
728 Ok(Value::Bool(true))
729}
730pub(crate) fn str_to_well_formed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
732 Ok(Value::str(this_str_c(it, &t)?))
733}
734pub(crate) const NFD_TABLE: &[(char, char, char)] = &[
745 ('À', 'A', '\u{0300}'), ('Á', 'A', '\u{0301}'), ('Â', 'A', '\u{0302}'),
746 ('Ã', 'A', '\u{0303}'), ('Ä', 'A', '\u{0308}'), ('Å', 'A', '\u{030A}'),
747 ('Ç', 'C', '\u{0327}'),
748 ('È', 'E', '\u{0300}'), ('É', 'E', '\u{0301}'), ('Ê', 'E', '\u{0302}'), ('Ë', 'E', '\u{0308}'),
749 ('Ì', 'I', '\u{0300}'), ('Í', 'I', '\u{0301}'), ('Î', 'I', '\u{0302}'), ('Ï', 'I', '\u{0308}'),
750 ('Ñ', 'N', '\u{0303}'),
751 ('Ò', 'O', '\u{0300}'), ('Ó', 'O', '\u{0301}'), ('Ô', 'O', '\u{0302}'),
752 ('Õ', 'O', '\u{0303}'), ('Ö', 'O', '\u{0308}'),
753 ('Ù', 'U', '\u{0300}'), ('Ú', 'U', '\u{0301}'), ('Û', 'U', '\u{0302}'), ('Ü', 'U', '\u{0308}'),
754 ('Ý', 'Y', '\u{0301}'),
755 ('à', 'a', '\u{0300}'), ('á', 'a', '\u{0301}'), ('â', 'a', '\u{0302}'),
756 ('ã', 'a', '\u{0303}'), ('ä', 'a', '\u{0308}'), ('å', 'a', '\u{030A}'),
757 ('ç', 'c', '\u{0327}'),
758 ('è', 'e', '\u{0300}'), ('é', 'e', '\u{0301}'), ('ê', 'e', '\u{0302}'), ('ë', 'e', '\u{0308}'),
759 ('ì', 'i', '\u{0300}'), ('í', 'i', '\u{0301}'), ('î', 'i', '\u{0302}'), ('ï', 'i', '\u{0308}'),
760 ('ñ', 'n', '\u{0303}'),
761 ('ò', 'o', '\u{0300}'), ('ó', 'o', '\u{0301}'), ('ô', 'o', '\u{0302}'),
762 ('õ', 'o', '\u{0303}'), ('ö', 'o', '\u{0308}'),
763 ('ù', 'u', '\u{0300}'), ('ú', 'u', '\u{0301}'), ('û', 'u', '\u{0302}'), ('ü', 'u', '\u{0308}'),
764 ('ý', 'y', '\u{0301}'), ('ÿ', 'y', '\u{0308}'),
765];
766pub(crate) fn japanese_voiced_sound_decompose(c: char) -> Option<(char, char)> {
767 let cp = c as u32;
768 match cp {
769 0x304C | 0x304E | 0x3050 | 0x3052 | 0x3054 |
770 0x3056 | 0x3058 | 0x305A | 0x305C | 0x305E |
771 0x3060 | 0x3062 | 0x3065 | 0x3067 | 0x3069 |
772 0x3070 | 0x3073 | 0x3076 | 0x3079 | 0x307C |
773 0x30AC | 0x30AE | 0x30B0 | 0x30B2 | 0x30B4 |
774 0x30B6 | 0x30B8 | 0x30BA | 0x30BC | 0x30BE |
775 0x30C0 | 0x30C2 | 0x30C5 | 0x30C7 | 0x30C9 |
776 0x30D0 | 0x30D3 | 0x30D6 | 0x30D9 | 0x30DC => {
777 char::from_u32(cp - 1).map(|b| (b, '\u{3099}'))
778 }
779 0x3071 | 0x3074 | 0x3077 | 0x307A | 0x307D |
780 0x30D1 | 0x30D4 | 0x30D7 | 0x30DA | 0x30DD => {
781 char::from_u32(cp - 2).map(|b| (b, '\u{309A}'))
782 }
783 0x30F4 => Some(('ウ', '\u{3099}')),
784 _ => None,
785 }
786}
787
788pub(crate) fn japanese_voiced_sound_compose(base: char, mark: char) -> Option<char> {
789 if mark != '\u{3099}' && mark != '\u{309A}' && mark != '\u{309B}' && mark != '\u{309C}' {
790 return None;
791 }
792 let b = base as u32;
793 let is_dakuten = mark == '\u{3099}' || mark == '\u{309B}';
794 let is_handakuten = mark == '\u{309A}' || mark == '\u{309C}';
795
796 match b {
797 0x304B | 0x304D | 0x304F | 0x3051 | 0x3053 |
798 0x3055 | 0x3057 | 0x3059 | 0x305B | 0x305D |
799 0x305F | 0x3061 | 0x3064 | 0x3066 | 0x3068 |
800 0x306F | 0x3072 | 0x3075 | 0x3078 | 0x307B |
801 0x30AB | 0x30AD | 0x30AF | 0x30B1 | 0x30B3 |
802 0x30B5 | 0x30B7 | 0x30B9 | 0x30BB | 0x30BD |
803 0x30BF | 0x30C1 | 0x30C4 | 0x30C6 | 0x30C8 |
804 0x30CF | 0x30D2 | 0x30D5 | 0x30D8 | 0x30DB if is_dakuten => {
805 char::from_u32(b + 1)
806 }
807 0x306F | 0x3072 | 0x3075 | 0x3078 | 0x307B |
808 0x30CF | 0x30D2 | 0x30D5 | 0x30D8 | 0x30DB if is_handakuten => {
809 char::from_u32(b + 2)
810 }
811 0x30A6 if is_dakuten => Some('ヴ'),
812 _ => None,
813 }
814}
815
816pub(crate) fn nfd_decompose(s: &str) -> String {
817 const HANGUL_S_BASE: u32 = 0xAC00;
818 const HANGUL_L_BASE: u32 = 0x1100;
819 const HANGUL_V_BASE: u32 = 0x1161;
820 const HANGUL_T_BASE: u32 = 0x11A7;
821 const HANGUL_N_COUNT: u32 = 588;
822 const HANGUL_T_COUNT: u32 = 28;
823 const HANGUL_S_COUNT: u32 = 11172;
824
825 let mut out = String::with_capacity(s.len());
826 for c in s.chars() {
827 let cp = c as u32;
828 if (HANGUL_S_BASE..HANGUL_S_BASE + HANGUL_S_COUNT).contains(&cp) {
829 let s_index = cp - HANGUL_S_BASE;
830 let l_index = s_index / HANGUL_N_COUNT;
831 let v_index = (s_index % HANGUL_N_COUNT) / HANGUL_T_COUNT;
832 let t_index = s_index % HANGUL_T_COUNT;
833 if let Some(l) = char::from_u32(HANGUL_L_BASE + l_index) {
834 out.push(l);
835 }
836 if let Some(v) = char::from_u32(HANGUL_V_BASE + v_index) {
837 out.push(v);
838 }
839 if t_index > 0 {
840 if let Some(t) = char::from_u32(HANGUL_T_BASE + t_index) {
841 out.push(t);
842 }
843 }
844 continue;
845 }
846 if let Some((base, mark)) = japanese_voiced_sound_decompose(c) {
847 out.push(base);
848 out.push(mark);
849 continue;
850 }
851 match NFD_TABLE.iter().find(|(pre, _, _)| *pre == c) {
852 Some((_, base, mark)) => {
853 out.push(*base);
854 out.push(*mark);
855 }
856 None => out.push(c),
857 }
858 }
859 out
860}
861pub(crate) fn nfc_compose(s: &str) -> String {
862 const HANGUL_S_BASE: u32 = 0xAC00;
863 const HANGUL_L_BASE: u32 = 0x1100;
864 const HANGUL_V_BASE: u32 = 0x1161;
865 const HANGUL_T_BASE: u32 = 0x11A7;
866 const HANGUL_L_COUNT: u32 = 19;
867 const HANGUL_V_COUNT: u32 = 21;
868 const HANGUL_T_COUNT: u32 = 28;
869 const HANGUL_N_COUNT: u32 = 588;
870
871 let decomposed = nfd_decompose(s);
872 let mut out = String::with_capacity(decomposed.len());
873 let mut chars = decomposed.chars().peekable();
874 while let Some(c) = chars.next() {
875 let cp = c as u32;
876 if (HANGUL_L_BASE..HANGUL_L_BASE + HANGUL_L_COUNT).contains(&cp) {
877 if let Some(&next) = chars.peek() {
878 let np = next as u32;
879 if (HANGUL_V_BASE..HANGUL_V_BASE + HANGUL_V_COUNT).contains(&np) {
880 chars.next();
881 let l_index = cp - HANGUL_L_BASE;
882 let v_index = np - HANGUL_V_BASE;
883 let mut s_index = l_index * HANGUL_N_COUNT + v_index * HANGUL_T_COUNT;
884 if let Some(&t_next) = chars.peek() {
885 let tp = t_next as u32;
886 if tp > HANGUL_T_BASE && tp < HANGUL_T_BASE + HANGUL_T_COUNT {
887 chars.next();
888 let t_index = tp - HANGUL_T_BASE;
889 s_index += t_index;
890 }
891 }
892 if let Some(hangul) = char::from_u32(HANGUL_S_BASE + s_index) {
893 out.push(hangul);
894 continue;
895 }
896 }
897 }
898 }
899 if let Some(&next) = chars.peek() {
900 if let Some(composed) = japanese_voiced_sound_compose(c, next) {
901 out.push(composed);
902 chars.next();
903 continue;
904 }
905 if let Some((pre, _, _)) = NFD_TABLE.iter().find(|(_, base, mark)| *base == c && *mark == next) {
906 out.push(*pre);
907 chars.next();
908 continue;
909 }
910 }
911 out.push(c);
912 }
913 out
914}
915pub(crate) fn str_normalize(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
916 let s = this_str_c(it, &t)?;
917 let form = if matches!(arg(a, 0), Value::Undefined) {
918 String::from("NFC")
919 } else {
920 it.to_string_value(arg(a, 0))?
921 };
922 match form.as_str() {
923 "NFC" | "NFKC" => Ok(Value::str(nfc_compose(&s))),
924 "NFD" | "NFKD" => Ok(Value::str(nfd_decompose(&s))),
925 _ => Err(it.range_error("The normalization form should be one of NFC, NFD, NFKC, NFKD.")),
926 }
927}
928pub(crate) fn str_split(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
932 let rx = arg(a, 0);
933 if matches!(t, Value::Undefined | Value::Null) {
934 return Err(it.type_error("String.prototype.split called on null or undefined"));
935 }
936 if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_split_key(), arg(a, 1))? {
937 return Ok(v);
938 }
939 let s = this_str_c(it, &t)?.into_owned();
940 let lim = match arg(a, 1) {
942 Value::Undefined => 4294967295.0,
943 v => to_uint32(it.num_of(&v)?),
944 };
945 let limit = lim as usize;
946 let sep = if matches!(rx, Value::Undefined) { None } else { Some(it.to_string_value(rx)?) };
947 if limit == 0 {
948 return Ok(Value::Object(Obj::array(Vec::new())));
949 }
950 let mut items: Vec<Value> = match sep {
951 None => vec![Value::str(s)],
952 Some(sep) => {
953 if sep.is_empty() {
954 let u = Units::of(&s);
955 (0..u.len().min(limit)).map(|i| Value::str(u.slice(i, i + 1))).collect()
956 } else if s.is_empty() {
957 vec![Value::str(s)]
958 } else {
959 s.split(&sep as &str).take(limit).map(|p| Value::str(p.to_string())).collect()
960 }
961 }
962 };
963 items.truncate(limit);
964 Ok(Value::Object(Obj::array(items)))
965}
966pub(crate) fn str_replace(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
967 let rx = arg(a, 0);
968 if matches!(t, Value::Undefined | Value::Null) {
969 return Err(it.type_error("String.prototype.replace called on null or undefined"));
970 }
971 if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_replace_key(), arg(a, 1))? {
972 return Ok(v);
973 }
974 let s = this_str_c(it, &t)?.into_owned();
975 let from = to_str_strict(it, rx)?;
976 let repl = arg(a, 1);
977 Ok(Value::str(replace_string_pattern(it, &s, &from, repl, false)?))
978}
979pub(crate) fn str_replace_all(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
981 let rx = arg(a, 0);
983 if matches!(t, Value::Undefined | Value::Null) {
984 return Err(it.type_error("String.prototype.replaceAll called on null or undefined"));
985 }
986 replace_all_precheck(it, &rx)?;
987 if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_replace_key(), arg(a, 1))? {
988 return Ok(v);
989 }
990 let s = this_str_c(it, &t)?.into_owned();
991 let from = to_str_strict(it, rx)?;
992 let repl = arg(a, 1);
993 Ok(Value::str(replace_string_pattern(it, &s, &from, repl, true)?))
994}
995pub(crate) fn str_repeat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1001 let t = this_val(it, &t)?;
1002 let n = it.num_of(&arg(a, 0))?;
1003 if n.is_nan() {
1004 return Ok(Value::str(String::new()));
1005 }
1006 if n < 0.0 || n == f64::INFINITY {
1007 return Err(it.range_error("Invalid count value"));
1008 }
1009 Ok(Value::str(this_str_c(it, &t)?.repeat(n as usize)))
1010}
1011pub(crate) fn str_concat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1012 let mut s = this_str_c(it, &t)?.into_owned();
1013 for v in a {
1014 s.push_str(&to_str_strict(it, v.clone())?);
1015 }
1016 Ok(Value::str(s))
1017}
1018pub(crate) fn str_pad_start(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1019 let s = this_str_c(it, &t)?.into_owned();
1020 let target = to_length_u64_checked(it, &arg(a, 0))? as usize;
1021 let pad = if matches!(arg(a, 1), Value::Undefined) {
1022 String::from(" ")
1023 } else {
1024 to_str_strict(it, arg(a, 1))?
1025 };
1026 Ok(Value::str(pad_str(&s, target, &pad, true)))
1027}
1028pub(crate) fn str_pad_end(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1029 let s = this_str_c(it, &t)?.into_owned();
1030 let target = to_length_u64_checked(it, &arg(a, 0))? as usize;
1031 let pad = if matches!(arg(a, 1), Value::Undefined) {
1032 String::from(" ")
1033 } else {
1034 to_str_strict(it, arg(a, 1))?
1035 };
1036 Ok(Value::str(pad_str(&s, target, &pad, false)))
1037}
1038
1039pub fn number_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1041 let pair = match key {
1042 "toFixed" => ("toFixed", num_to_fixed as NativeFn),
1043 "toString" => ("Number.toString", num_to_string as NativeFn),
1044 "toExponential" => ("toExponential", num_to_exponential as NativeFn),
1045 "toPrecision" => ("toPrecision", num_to_precision as NativeFn),
1046 "valueOf" => ("valueOf", num_value_of as NativeFn),
1047 "toLocaleString" => ("toLocaleString", num_to_locale_string as NativeFn),
1048 _ => return None,
1049 };
1050 Some(pair)
1051}
1052
1053pub fn number_get(n: f64, key: &str) -> Value {
1055 let _ = n;
1056 number_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1057}
1058pub(crate) fn num_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1059 Ok(Value::Number(this_number(it, &t, "valueOf")?))
1060}
1061pub fn boolean_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1069 let pair = match key {
1070 "toString" => ("toString", bool_to_string as NativeFn),
1071 "valueOf" => ("valueOf", bool_value_of as NativeFn),
1072 _ => return None,
1073 };
1074 Some(pair)
1075}
1076
1077pub fn boolean_get(_b: bool, key: &str) -> Value {
1078 boolean_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1079}
1080pub(crate) fn bool_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1081 Ok(Value::str(if this_boolean(it, &t, "toString")? { "true" } else { "false" }))
1082}
1083pub(crate) fn bool_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1084 Ok(Value::Bool(this_boolean(it, &t, "valueOf")?))
1085}
1086pub(crate) fn normalize_mantissa(abs_n: f64) -> (f64, i32) {
1089 if abs_n == 0.0 {
1090 return (0.0, 0);
1091 }
1092 let mut exp = libm::floor(libm::log10(abs_n)) as i32;
1093 let mut mantissa = abs_n / libm::pow(10.0, exp as f64);
1094 if mantissa >= 10.0 {
1095 mantissa /= 10.0;
1096 exp += 1;
1097 } else if mantissa < 1.0 {
1098 mantissa *= 10.0;
1099 exp -= 1;
1100 }
1101 (mantissa, exp)
1102}
1103pub(crate) fn num_to_exponential(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1107 let n = this_number(it, &t, "toExponential")?;
1108 let digits = match arg(a, 0) {
1109 Value::Undefined => None,
1110 v => {
1111 let d = it.num_of(&v)?;
1112 Some(if d.is_nan() { 0.0 } else { libm::trunc(d) })
1113 }
1114 };
1115 if !n.is_finite() {
1116 return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1117 }
1118 let digits = match digits {
1119 None => None,
1120 Some(d) if (0.0..=100.0).contains(&d) => Some(d as usize),
1121 Some(_) => return Err(it.range_error("toExponential() argument must be between 0 and 100")),
1122 };
1123 Ok(Value::str(crate::os_lib::ecma::numfmt::to_exponential(n, digits)))
1124}
1125pub(crate) fn num_to_precision(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1129 let n = this_number(it, &t, "toPrecision")?;
1130 if matches!(arg(a, 0), Value::Undefined) {
1131 return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1132 }
1133 let p = libm::trunc(it.num_of(&arg(a, 0))?);
1134 if !n.is_finite() {
1135 return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1136 }
1137 if !(1.0..=100.0).contains(&p) {
1138 return Err(it.range_error("toPrecision() argument must be between 1 and 100"));
1139 }
1140 Ok(Value::str(crate::os_lib::ecma::numfmt::to_precision(n, p as usize)))
1141}
1142pub(crate) fn num_to_fixed(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1148 let n = this_number(it, &t, "toFixed")?;
1149 let digits = match arg(a, 0) {
1150 Value::Undefined => 0.0,
1151 v => {
1152 let d = it.num_of(&v)?;
1153 if d.is_nan() { 0.0 } else { libm::trunc(d) }
1154 }
1155 };
1156 if !(0.0..=100.0).contains(&digits) {
1157 return Err(it.range_error("toFixed() digits argument must be between 0 and 100"));
1158 }
1159 Ok(Value::str(crate::os_lib::ecma::numfmt::to_fixed(n, digits as usize)))
1160}
1161pub(crate) fn num_to_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1164 let n = this_number(it, &t, "toString")?;
1165 let radix = match arg(a, 0) {
1166 Value::Undefined => 10.0,
1167 v => {
1168 let r = it.num_of(&v)?;
1169 if r.is_nan() { 0.0 } else { libm::trunc(r) }
1170 }
1171 };
1172 if !(2.0..=36.0).contains(&radix) {
1173 return Err(it.range_error("toString() radix must be between 2 and 36"));
1174 }
1175 if radix == 10.0 {
1176 return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1177 }
1178 Ok(Value::str(crate::os_lib::ecma::numfmt::to_radix(n, radix as u32)))
1179}
1180pub(crate) fn num_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1186 let n = if matches!(t, Value::BigInt(_)) { t.to_number() } else { this_number(it, &t, "toLocaleString")? };
1189 let opts = super::intl::build_nf_options(it, &arg(a, 0), &arg(a, 1))?;
1190 Ok(Value::str(crate::os_lib::ecma::numloc::format(n, &opts)))
1191}
1192pub(crate) const RADIX_DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
1193pub(crate) fn format_radix(num: f64, radix: u32) -> String {
1194 if num.is_nan() {
1195 return String::from("NaN");
1196 }
1197 if num.is_infinite() {
1198 return String::from(if num > 0.0 { "Infinity" } else { "-Infinity" });
1199 }
1200 let neg = num < 0.0;
1201 let n = libm::fabs(num);
1202 let int_n = libm::floor(n);
1203 let mut frac = n - int_n;
1204 let mut int_digits = Vec::new();
1205 let mut i = int_n;
1206 if i == 0.0 {
1207 int_digits.push(b'0');
1208 }
1209 while i >= 1.0 {
1210 let rem = libm::fmod(i, radix as f64) as usize;
1211 int_digits.push(RADIX_DIGITS[rem.min(35)]);
1212 i = libm::floor(i / radix as f64);
1213 }
1214 int_digits.reverse();
1215 let mut s = String::from_utf8(int_digits).unwrap_or_default();
1216 if frac > 0.0 {
1217 s.push('.');
1218 let mut count = 0;
1219 while frac > 0.0 && count < 20 {
1220 frac *= radix as f64;
1221 let d = libm::floor(frac) as usize;
1222 s.push(RADIX_DIGITS[d.min(35)] as char);
1223 frac -= libm::floor(frac);
1224 count += 1;
1225 }
1226 }
1227 if neg {
1228 format!("-{}", s)
1229 } else {
1230 s
1231 }
1232}
1233
1234pub fn bigint_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1236 let pair = match key {
1237 "toString" => ("toString", bigint_to_string as NativeFn),
1238 "valueOf" => ("valueOf", bigint_value_of as NativeFn),
1239 "toLocaleString" => ("toLocaleString", bigint_to_locale_string as NativeFn),
1240 _ => return None,
1241 };
1242 Some(pair)
1243}
1244
1245pub(crate) fn bigint_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1246 let bi_str = match &t {
1247 Value::BigInt(b) => b.to_radix_string(10),
1248 Value::Object(o) => match o.borrow().primitive() {
1249 Some(Value::BigInt(b)) => b.to_radix_string(10),
1250 _ => return Err(it.type_error("BigInt.prototype.toLocaleString requires that 'this' be a BigInt")),
1251 },
1252 _ => return Err(it.type_error("BigInt.prototype.toLocaleString requires that 'this' be a BigInt")),
1253 };
1254 let opts = super::intl::build_nf_options(it, &arg(a, 0), &arg(a, 1))?;
1255 let nv = crate::os_lib::ecma::numloc::NumValue::from_int_str(&bi_str);
1256 Ok(Value::str(crate::os_lib::ecma::numloc::format_value(&nv, &opts)))
1257}
1258
1259pub fn bigint_get(b: &alloc::rc::Rc<super::super::bigint::BigInt>, key: &str) -> Value {
1261 let _ = b;
1262 bigint_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1263}
1264pub(crate) fn bigint_to_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1265 let bi_val = match &t {
1266 Value::BigInt(_) => t.clone(),
1267 Value::Object(o) => match o.borrow().primitive() {
1268 Some(p @ Value::BigInt(_)) => p.clone(),
1269 _ => return Err(it.type_error("BigInt.prototype.toString requires that 'this' be a BigInt")),
1270 },
1271 _ => return Err(it.type_error("BigInt.prototype.toString requires that 'this' be a BigInt")),
1272 };
1273 if let (Value::BigInt(b), Some(r)) = (&bi_val, a.first().filter(|v| !matches!(v, Value::Undefined))) {
1275 let n = it.num_of(r)?;
1276 let radix = to_integer_or_infinity(n);
1277 if !(2.0..=36.0).contains(&radix) {
1278 return Err(it.range_error("toString() radix must be between 2 and 36"));
1279 }
1280 return Ok(Value::str(b.to_radix_string(radix as u32)));
1281 }
1282 Ok(Value::str(bi_val.to_js_string()))
1283}
1284pub(crate) fn bigint_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1285 match &t {
1286 Value::BigInt(_) => Ok(t),
1287 Value::Object(o) => match o.borrow().primitive() {
1288 Some(p @ Value::BigInt(_)) => Ok(p.clone()),
1289 _ => Err(it.type_error("BigInt.prototype.valueOf requires that 'this' be a BigInt")),
1290 },
1291 _ => Err(it.type_error("BigInt.prototype.valueOf requires that 'this' be a BigInt")),
1292 }
1293}
1294
1295pub(crate) fn bigint_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1298 use super::super::bigint::BigInt;
1299 let raw = a.first().cloned().unwrap_or(Value::Undefined);
1300 let arg = if matches!(raw, Value::Object(_)) {
1301 it.to_primitive(raw, "number")?
1302 } else {
1303 raw
1304 };
1305 let bi = match &arg {
1306 Value::BigInt(b) => (**b).clone(),
1307 Value::Number(n) => match BigInt::from_f64(*n) {
1308 Some(v) => v,
1309 None => {
1310 return Err(it.range_error("The number cannot be converted to a BigInt because it is not an integer"));
1311 }
1312 },
1313 Value::Bool(b) => BigInt::from_i64(if *b { 1 } else { 0 }),
1314 Value::Str(s) => match BigInt::parse_js_string(s) {
1315 Some(v) => v,
1316 None => return Err(it.syntax_error("Cannot convert string to a BigInt")),
1317 },
1318 _ => return Err(it.type_error("Cannot convert value to a BigInt")),
1319 };
1320 Ok(Value::bigint(bi))
1321}
1322
1323pub(crate) fn bits_arg(it: &mut Interp, a: &[Value]) -> Result<u64, Value> {
1325 let raw = arg(a, 0);
1326 if matches!(raw, Value::Undefined) {
1327 return Ok(0);
1328 }
1329 let n = it.num_of(&raw)?;
1330 let int = to_integer_or_infinity(n);
1331 if !(0.0..=MAX_SAFE_INT_F64).contains(&int) {
1332 return Err(it.range_error("Invalid bits value for BigInt.asIntN/asUintN"));
1333 }
1334 Ok(int as u64)
1335}
1336
1337pub(crate) fn bigint_arg(it: &mut Interp, a: &[Value]) -> Result<super::super::bigint::BigInt, Value> {
1339 use super::super::bigint::BigInt;
1340 let raw = arg(a, 1);
1341 let prim = if matches!(raw, Value::Object(_)) {
1342 it.to_primitive(raw, "number")?
1343 } else {
1344 raw
1345 };
1346 match &prim {
1347 Value::BigInt(b) => Ok((**b).clone()),
1348 Value::Bool(b) => Ok(BigInt::from_i64(if *b { 1 } else { 0 })),
1349 Value::Str(s) if !is_symbol_like_key(s) => match BigInt::parse_js_string(s) {
1350 Some(v) => Ok(v),
1351 None => Err(it.syntax_error("Cannot convert string to a BigInt")),
1352 },
1353 _ => Err(it.type_error("Cannot convert value to a BigInt")),
1354 }
1355}
1356
1357pub(crate) fn bigint_as_int_n(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1359 let bits = bits_arg(it, a)?;
1360 let v = bigint_arg(it, a)?;
1361 Ok(Value::bigint(v.as_int_n(bits)))
1362}
1363
1364pub(crate) fn bigint_as_uint_n(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1366 let bits = bits_arg(it, a)?;
1367 let v = bigint_arg(it, a)?;
1368 Ok(Value::bigint(v.as_uint_n(bits)))
1369}
1370
1371pub fn array_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1376 let pair = match key {
1377 "push" => ("push", arr_push as NativeFn),
1378 "pop" => ("pop", arr_pop as NativeFn),
1379 "shift" => ("shift", arr_shift as NativeFn),
1380 "unshift" => ("unshift", arr_unshift as NativeFn),
1381 "slice" => ("slice", arr_slice as NativeFn),
1382 "indexOf" => ("indexOf", arr_index_of as NativeFn),
1383 "includes" => ("includes", arr_includes as NativeFn),
1384 "join" => ("join", arr_join as NativeFn),
1385 "concat" => ("concat", arr_concat as NativeFn),
1386 "reverse" => ("reverse", arr_reverse as NativeFn),
1387 "map" => ("map", arr_map_g as NativeFn),
1388 "filter" => ("filter", arr_filter_g as NativeFn),
1389 "forEach" => ("forEach", arr_for_each_g as NativeFn),
1390 "reduce" => ("reduce", arr_reduce_g as NativeFn),
1391 "find" => ("find", arr_find as NativeFn),
1392 "findIndex" => ("findIndex", arr_find_index as NativeFn),
1393 "some" => ("some", arr_some_g as NativeFn),
1394 "every" => ("every", arr_every_g as NativeFn),
1395 "sort" => ("sort", arr_sort as NativeFn),
1396 "fill" => ("fill", arr_fill as NativeFn),
1397 "flat" => ("flat", arr_flat as NativeFn),
1398 "flatMap" => ("flatMap", arr_flat_map as NativeFn),
1399 "at" => ("at", arr_at as NativeFn),
1400 "findLast" => ("findLast", arr_find_last_safe as NativeFn),
1401 "findLastIndex" => ("findLastIndex", arr_find_last_index_safe as NativeFn),
1402 "entries" => ("entries", arr_entries as NativeFn),
1403 "keys" => ("keys", arr_keys as NativeFn),
1404 "values" => ("values", arr_values as NativeFn),
1405 "Symbol(Symbol.iterator)" => ("[Symbol.iterator]", arr_values as NativeFn),
1406 "reduceRight" => ("reduceRight", arr_reduce_right_safe as NativeFn),
1407 "toString" => ("toString", arr_to_string as NativeFn),
1408 "toLocaleString" => ("toLocaleString", arr_to_locale_string as NativeFn),
1409 "splice" => ("splice", arr_splice as NativeFn),
1410 "lastIndexOf" => ("lastIndexOf", arr_last_index_of as NativeFn),
1411 "copyWithin" => ("copyWithin", arr_copy_within as NativeFn),
1412 "toSorted" => ("toSorted", arr_to_sorted as NativeFn),
1413 "toReversed" => ("toReversed", arr_to_reversed as NativeFn),
1414 "toSpliced" => ("toSpliced", arr_to_spliced as NativeFn),
1415 "with" => ("with", arr_with as NativeFn),
1416 _ => return None,
1417 };
1418 Some(pair)
1419}
1420
1421pub fn object_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1423 let pair = match key {
1424 "hasOwnProperty" => ("hasOwnProperty", obj_has_own as NativeFn),
1425 "toString" => ("toString", obj_to_string as NativeFn),
1426 "toLocaleString" => ("toLocaleString", obj_to_locale_string as NativeFn),
1427 "valueOf" => ("valueOf", obj_value_of as NativeFn),
1428 "isPrototypeOf" => ("isPrototypeOf", obj_is_prototype_of as NativeFn),
1429 "propertyIsEnumerable" => ("propertyIsEnumerable", obj_property_is_enumerable as NativeFn),
1430 "__defineGetter__" => ("__defineGetter__", obj_define_getter as NativeFn),
1431 "__defineSetter__" => ("__defineSetter__", obj_define_setter as NativeFn),
1432 "__lookupGetter__" => ("__lookupGetter__", obj_lookup_getter as NativeFn),
1433 "__lookupSetter__" => ("__lookupSetter__", obj_lookup_setter as NativeFn),
1434 _ => return None,
1435 };
1436 Some(pair)
1437}
1438
1439pub(crate) fn obj_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1440 if matches!(t, Value::Undefined | Value::Null) {
1441 return Err(it.type_error("Cannot convert undefined or null to object"));
1442 }
1443 to_object_required(it, &t, "valueOf")
1445}
1446
1447pub fn object_get(o: &ObjRef, key: &str) -> Value {
1449 let is_array = matches!(o.borrow().kind, ObjKind::Array(_));
1450 if is_array {
1451 if let Some((name, f)) = array_builtin_fn(key) {
1452 return nv(name, f);
1453 }
1454 }
1455 if let Some((name, f)) = object_builtin_fn(key) {
1456 return nv(name, f);
1457 }
1458 Value::Undefined
1459}
1460fn to_object_required(it: &mut Interp, v: &Value, method: &str) -> Result<Value, Value> {
1461 if matches!(v, Value::Undefined | Value::Null) {
1462 return Err(it.type_error(alloc::format!(
1463 "Object.prototype.{} called on null or undefined",
1464 method
1465 )));
1466 }
1467 if matches!(v, Value::Object(_)) {
1468 Ok(v.clone())
1469 } else {
1470 super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(v))
1471 }
1472}
1473
1474fn define_accessor_legacy(
1475 it: &mut Interp,
1476 this: Value,
1477 a: &[Value],
1478 is_getter: bool,
1479 method: &str,
1480) -> Result<Value, Value> {
1481 let obj = to_object_required(it, &this, method)?;
1482 let f = arg(a, 1);
1483 if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
1484 return Err(it.type_error("Accessor must be a function"));
1485 }
1486 let pk = it.prim_key(arg(a, 0))?;
1487 let key = super::super::interp::to_property_key(&pk).into_owned();
1488 let desc = Obj::plain();
1489 {
1490 let mut db = desc.borrow_mut();
1491 db.props.insert(if is_getter { "get" } else { "set" }.into(), f);
1492 db.props.insert("enumerable".into(), Value::Bool(true));
1493 db.props.insert("configurable".into(), Value::Bool(true));
1494 }
1495 super::extra_static::object_define_property(
1496 it,
1497 Value::Undefined,
1498 &[obj, Value::str(key), Value::Object(desc)],
1499 )?;
1500 Ok(Value::Undefined)
1501}
1502
1503fn lookup_accessor_legacy(
1504 it: &mut Interp,
1505 this: Value,
1506 a: &[Value],
1507 is_getter: bool,
1508 method: &str,
1509) -> Result<Value, Value> {
1510 let mut cur = to_object_required(it, &this, method)?;
1511 let pk = it.prim_key(arg(a, 0))?;
1512 let key = Value::str(super::super::interp::to_property_key(&pk).into_owned());
1513 for _ in 0..1000 {
1514 let desc = super::extra_static::object_get_own_property_descriptor(
1515 it,
1516 Value::Undefined,
1517 &[cur.clone(), key.clone()],
1518 )?;
1519 if !matches!(desc, Value::Undefined) {
1520 let has_data = if let Value::Object(d) = &desc {
1521 let db = d.borrow();
1522 db.props.contains_key("value") || db.props.contains_key("writable")
1523 } else {
1524 false
1525 };
1526 if has_data {
1527 return Ok(Value::Undefined);
1528 }
1529 return it.get_property(&desc, if is_getter { "get" } else { "set" });
1530 }
1531 cur = super::extra_static::object_get_prototype_of(it, Value::Undefined, &[cur])?;
1532 if !matches!(cur, Value::Object(_)) {
1533 break;
1534 }
1535 }
1536 Ok(Value::Undefined)
1537}
1538
1539pub(crate) fn obj_define_getter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1540 define_accessor_legacy(it, this, a, true, "__defineGetter__")
1541}
1542pub(crate) fn obj_define_setter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1543 define_accessor_legacy(it, this, a, false, "__defineSetter__")
1544}
1545pub(crate) fn obj_lookup_getter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1546 lookup_accessor_legacy(it, this, a, true, "__lookupGetter__")
1547}
1548pub(crate) fn obj_lookup_setter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1549 lookup_accessor_legacy(it, this, a, false, "__lookupSetter__")
1550}
1551
1552pub(crate) fn this_items(this: &Value) -> Vec<Value> {
1558 if let Value::Object(o) = this {
1559 let o = unwrap_proxy_target(o);
1560 let b = o.borrow();
1561 if let ObjKind::Array(items) = &b.kind {
1562 return items.clone();
1563 }
1564 if let ObjKind::Bytes(st) = &b.kind {
1565 return st.values();
1566 }
1567 }
1568 Vec::new()
1569}
1570pub(crate) fn this_objref(this: &Value) -> Option<ObjRef> {
1573 if let Value::Object(o) = this {
1574 Some(unwrap_proxy_target(o))
1575 } else {
1576 None
1577 }
1578}
1579
1580const MAX_SAFE_INT_U64: u64 = 9_007_199_254_740_991;
1582const MAX_SAFE_INT_F64: f64 = 9_007_199_254_740_991.0;
1583
1584fn to_integer_or_infinity(n: f64) -> f64 {
1585 if n.is_nan() || n == 0.0 {
1586 0.0
1587 } else if n.is_infinite() {
1588 n
1589 } else {
1590 libm::trunc(n)
1591 }
1592}
1593
1594pub(crate) fn to_length_u64(v: &Value) -> u64 {
1595 let n = to_integer_or_infinity(v.to_number());
1596 if n <= 0.0 {
1597 0
1598 } else if n >= MAX_SAFE_INT_F64 {
1599 MAX_SAFE_INT_U64
1600 } else {
1601 n as u64
1602 }
1603}
1604
1605pub(crate) fn to_length_u64_checked(it: &mut Interp, v: &Value) -> Result<u64, Value> {
1606 let n = to_integer_or_infinity(it.num_of(v)?);
1607 Ok(if n <= 0.0 {
1608 0
1609 } else if n >= MAX_SAFE_INT_F64 {
1610 MAX_SAFE_INT_U64
1611 } else {
1612 n as u64
1613 })
1614}
1615
1616fn norm_index_u64(v: f64, len: u64) -> u64 {
1617 let int = to_integer_or_infinity(v);
1618 if int == f64::NEG_INFINITY {
1619 0
1620 } else if int == f64::INFINITY || int >= (len as f64) {
1621 len
1622 } else if int < 0.0 {
1623 let abs = -int;
1624 if abs >= (len as f64) {
1625 0
1626 } else {
1627 len - (abs as u64)
1628 }
1629 } else {
1630 (int as u64).min(len)
1631 }
1632}
1633
1634fn from_index_u64(a: &[Value], len: u64) -> Option<u64> {
1635 if len == 0 {
1636 return None;
1637 }
1638 if a.len() < 2 || matches!(arg(a, 1), Value::Undefined) {
1639 return Some(0);
1640 }
1641 let n = to_integer_or_infinity(arg(a, 1).to_number());
1642 if n == f64::INFINITY || n >= (len as f64) {
1643 return None;
1644 }
1645 if n == f64::NEG_INFINITY {
1646 return Some(0);
1647 }
1648 if n >= 0.0 {
1649 Some((n as u64).min(len))
1650 } else {
1651 let abs = -n;
1652 if abs >= (len as f64) {
1653 Some(0)
1654 } else {
1655 Some(len - (abs as u64))
1656 }
1657 }
1658}
1659
1660fn is_direct_array(t: &Value) -> bool {
1661 matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)))
1662}
1663
1664fn is_dense_plain_array(t: &Value) -> bool {
1665 matches!(t, Value::Object(o) if {
1666 let b = o.borrow();
1667 matches!(b.kind, ObjKind::Array(_)) && b.holes().is_none() && b.accessors().is_none()
1668 })
1669}
1670
1671fn is_js_array(t: &Value) -> bool {
1672 matches!(t, Value::Object(o) if matches!(unwrap_proxy_target(o).borrow().kind, ObjKind::Array(_)))
1673}
1674
1675fn try_vec_with_capacity<T>(it: &mut Interp, cap: usize) -> Result<Vec<T>, Value> {
1676 if cap > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
1677 return Err(it.range_error("Invalid array length"));
1678 }
1679 let mut v = Vec::new();
1680 if cap > 0 && v.try_reserve_exact(cap).is_err() {
1681 return Err(it.range_error("Invalid array length"));
1682 }
1683 Ok(v)
1684}
1685
1686fn next_proto_for_elem(it: &Interp, cur: &ObjRef) -> Option<ObjRef> {
1687 let b = cur.borrow();
1688 if let Some(p) = &b.proto {
1689 return Some(p.clone());
1690 }
1691 if b.is_null_proto() {
1692 return None;
1693 }
1694 if let (ObjKind::Plain, Some(prim)) = (&b.kind, b.primitive()) {
1695 let cname = match prim {
1696 Value::Str(_) => Some("String"),
1697 Value::Number(_) => Some("Number"),
1698 Value::Bool(_) => Some("Boolean"),
1699 _ => None,
1700 };
1701 if let Some(p) = cname.and_then(|n| global_ctor_proto(it, n)) {
1702 if !Rc::ptr_eq(&p, cur) {
1703 return Some(p);
1704 }
1705 }
1706 }
1707 drop(b);
1708 implicit_proto(it, cur)
1709}
1710
1711fn has_array_elem(it: &mut Interp, t: &Value, key: &str) -> Result<bool, Value> {
1712 match t {
1713 Value::Object(o) => {
1714 let proxy = match &o.borrow().kind {
1716 ObjKind::Proxy(p) => Some((p.target.clone(), p.handler.clone())),
1717 _ => None,
1718 };
1719 if let Some((target, handler)) = proxy {
1720 let trap = handler.borrow().props.get("has").cloned();
1721 if let Some(trap) = trap.filter(|f| matches!(f, Value::Object(fn_o) if fn_o.borrow().is_callable())) {
1722 let args = [Value::Object(target), Value::str(key)];
1723 let res = it.call_value(&trap, Value::Object(handler), &args)?;
1724 return Ok(res.truthy());
1725 }
1726 return has_array_elem(it, &Value::Object(target), key);
1727 }
1728 let mut cur_opt = Some(o.clone());
1729 let mut guard = 0u32;
1730 while let Some(cur) = cur_opt {
1731 let host_ref = cur.borrow().kind.host_ref();
1732 if let Some(h) = host_ref {
1733 if !matches!(
1734 (it.host.own)(it, h, key),
1735 crate::os_lib::ecma::host::HostOwn::Generic
1736 | crate::os_lib::ecma::host::HostOwn::Absent
1737 ) {
1738 return Ok(true);
1739 }
1740 if (it.host.resolves_on_read)(h) && (it.host.get)(it, &cur, h, key).is_some() {
1741 return Ok(true);
1742 }
1743 }
1744 {
1745 let b = cur.borrow();
1746 let is_arr = matches!(&b.kind, ObjKind::Array(_));
1747 match &b.kind {
1748 ObjKind::Array(items) => {
1749 if key == "length" {
1750 return Ok(true);
1751 }
1752 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1753 if idx < items.len() && !b.is_hole(idx) {
1754 return Ok(true);
1755 }
1756 }
1757 }
1758 ObjKind::Bytes(st)
1759 if key == "length"
1760 || crate::os_lib::ecma::value::parse_index(key).is_some_and(|idx| idx < st.len) =>
1761 {
1762 return Ok(true);
1763 }
1764 ObjKind::Plain => {
1765 if let Some(Value::Str(s)) = b.primitive() {
1766 if key == "length"
1767 || crate::os_lib::ecma::value::parse_index(key)
1768 .is_some_and(|idx| idx < Units::of(s).len())
1769 {
1770 return Ok(true);
1771 }
1772 }
1773 }
1774 _ => {}
1775 }
1776 let array_hole_index = is_arr && crate::os_lib::ecma::value::parse_index(key).is_some();
1777 if (!array_hole_index && b.props.contains_key(key)) || b.has_accessor(key) {
1778 return Ok(true);
1779 }
1780 }
1781 guard += 1;
1782 if guard > 1000 {
1783 break;
1784 }
1785 cur_opt = next_proto_for_elem(it, &cur);
1786 }
1787 Ok(false)
1788 }
1789 Value::Str(s) => {
1790 if key == "length"
1791 || crate::os_lib::ecma::value::parse_index(key).is_some_and(|idx| idx < Units::of(s).len())
1792 {
1793 return Ok(true);
1794 }
1795 match global_ctor_proto(it, "String") {
1796 Some(p) => has_array_elem(it, &Value::Object(p), key),
1797 None => Ok(false),
1798 }
1799 }
1800 Value::Bool(_) => match global_ctor_proto(it, "Boolean") {
1801 Some(p) => has_array_elem(it, &Value::Object(p), key),
1802 None => Ok(false),
1803 },
1804 Value::Number(_) => match global_ctor_proto(it, "Number") {
1805 Some(p) => has_array_elem(it, &Value::Object(p), key),
1806 None => Ok(false),
1807 },
1808 Value::BigInt(_) => match global_ctor_proto(it, "BigInt") {
1809 Some(p) => has_array_elem(it, &Value::Object(p), key),
1810 None => Ok(false),
1811 },
1812 _ => Ok(false),
1813 }
1814}
1815
1816fn get_array_elem(it: &mut Interp, t: &Value, key: &str) -> Result<Value, Value> {
1817 if let Value::Object(o) = t {
1818 let arr_direct = matches!(&o.borrow().kind, ObjKind::Array(_));
1819 if arr_direct {
1820 enum Hit {
1821 Getter(Option<Value>),
1822 Prop(Value),
1823 Elem(Value),
1824 Proto,
1825 }
1826 let hit = {
1827 let b = o.borrow();
1828 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1829 let is_hole = matches!(&b.kind, ObjKind::Array(items) if idx < items.len() && b.is_hole(idx));
1830 if is_hole {
1831 Hit::Proto
1832 } else if let Some(acc) = b.get_accessor(key) {
1833 Hit::Getter(acc.get.clone())
1834 } else if let ObjKind::Array(items) = &b.kind {
1835 if idx < items.len() {
1836 Hit::Elem(items[idx].clone())
1837 } else {
1838 Hit::Proto
1839 }
1840 } else {
1841 Hit::Proto
1842 }
1843 } else if let Some(acc) = b.get_accessor(key) {
1844 Hit::Getter(acc.get.clone())
1845 } else if let Some(v) = b.props.get(key) {
1846 Hit::Prop(v.clone())
1847 } else {
1848 Hit::Proto
1849 }
1850 };
1851 return match hit {
1852 Hit::Getter(Some(g)) => it.call_value(&g, t.clone(), &[]),
1853 Hit::Getter(None) => Ok(Value::Undefined),
1854 Hit::Prop(v) | Hit::Elem(v) => Ok(v),
1855 Hit::Proto => {
1856 let start = implicit_proto(it, o);
1857 it.get_property_proto_chain(t, o, key, start)
1858 }
1859 };
1860 }
1861 }
1862 it.get_property(t, key)
1863}
1864
1865pub(crate) fn array_like_length(it: &mut Interp, t: &Value) -> usize {
1867 it.get_property(t, "length")
1868 .map(|l| to_length_u64(&l) as usize)
1869 .unwrap_or(0)
1870}
1871
1872pub(crate) enum ArrOp {
1882 Push(usize),
1883 Pop,
1884 Shift,
1885 Unshift(usize),
1886 Splice(usize, usize, usize),
1888 Fill(usize, usize),
1889 CopyWithin(usize, usize),
1891 Reverse,
1892 Sort,
1893}
1894
1895struct ArrLock {
1896 frozen: bool,
1897 sealed: bool,
1898 non_ext: bool,
1899 len_ro: bool,
1900}
1901
1902fn arr_lock(o: &ObjRef) -> Option<ArrLock> {
1903 let b = o.borrow();
1904 if !matches!(b.kind, ObjKind::Array(_)) || b.props.contains_key("_ta_kind") {
1905 return None;
1906 }
1907 let frozen = b.is_frozen();
1908 let sealed = frozen || b.is_sealed();
1909 let non_ext = sealed || b.is_non_extensible();
1910 let len_ro = frozen || b.get_attr("length").is_some_and(|a| !a.writable);
1911 let elem_attrs = b.attrs().is_some_and(|m| m.keys().any(|k| crate::os_lib::ecma::value::parse_index(k).is_some()));
1912 if !(non_ext || len_ro || elem_attrs) {
1913 return None;
1914 }
1915 Some(ArrLock { frozen, sealed, non_ext, len_ro })
1916}
1917
1918fn arr_elem_ro(o: &ObjRef, lk: &ArrLock, idx: usize) -> bool {
1920 if lk.frozen {
1921 return true;
1922 }
1923 let b = o.borrow();
1924 let ks = idx.to_string();
1925 if let Some(acc) = b.get_accessor(&ks) {
1926 return acc.set.is_none();
1927 }
1928 b.get_attr(&ks).is_some_and(|a| !a.writable)
1929}
1930fn arr_elem_nc(o: &ObjRef, lk: &ArrLock, idx: usize) -> bool {
1932 lk.sealed || o.borrow().get_attr(&idx.to_string()).is_some_and(|a| !a.configurable)
1933}
1934
1935pub(crate) fn arr_check(it: &mut Interp, o: &ObjRef, op: ArrOp) -> Result<(), Value> {
1936 let Some(lk) = arr_lock(o) else { return Ok(()) };
1937 let len = match &o.borrow().kind {
1938 ObjKind::Array(items) => items.len(),
1939 _ => 0,
1940 };
1941 let write = |it: &mut Interp, idx: usize| -> Result<(), Value> {
1943 if idx < len {
1944 if arr_elem_ro(o, &lk, idx) {
1945 return Err(it.type_error(alloc::format!(
1946 "Cannot assign to read only property '{}' of object '[object Array]'",
1947 idx
1948 )));
1949 }
1950 } else if lk.non_ext || lk.len_ro {
1951 return Err(it.type_error(alloc::format!("Cannot add property {}, object is not extensible", idx)));
1952 }
1953 Ok(())
1954 };
1955 let del = |it: &mut Interp, idx: usize| -> Result<(), Value> {
1956 if arr_elem_nc(o, &lk, idx) {
1957 return Err(it.type_error(alloc::format!("Cannot delete property '{}' of [object Array]", idx)));
1958 }
1959 Ok(())
1960 };
1961 let set_len = |it: &mut Interp| -> Result<(), Value> {
1962 if lk.len_ro {
1963 return Err(it.type_error("Cannot assign to read only property 'length' of object '[object Array]'"));
1964 }
1965 Ok(())
1966 };
1967 match op {
1968 ArrOp::Push(n) => {
1969 for i in 0..n {
1970 write(it, len + i)?;
1971 }
1972 set_len(it)
1973 }
1974 ArrOp::Pop => {
1975 if len > 0 {
1976 del(it, len - 1)?;
1977 }
1978 set_len(it)
1979 }
1980 ArrOp::Shift => {
1981 for i in 0..len.saturating_sub(1) {
1982 write(it, i)?;
1983 }
1984 if len > 0 {
1985 del(it, len - 1)?;
1986 }
1987 set_len(it)
1988 }
1989 ArrOp::Unshift(n) => {
1990 if n > 0 {
1991 for i in 0..len + n {
1992 write(it, i)?;
1993 }
1994 }
1995 set_len(it)
1996 }
1997 ArrOp::Splice(start, dc, ic) => {
1998 if ic < dc {
1999 for i in start + ic..len - dc + ic {
2000 write(it, i)?;
2001 }
2002 for i in len - dc + ic..len {
2003 del(it, i)?;
2004 }
2005 } else if ic > dc {
2006 for i in start + ic..len - dc + ic {
2007 write(it, i)?;
2008 }
2009 }
2010 for i in start..start + ic {
2011 write(it, i)?;
2012 }
2013 set_len(it)
2014 }
2015 ArrOp::Fill(start, end) => {
2016 for i in start..end {
2017 write(it, i)?;
2018 }
2019 Ok(())
2020 }
2021 ArrOp::CopyWithin(to, count) => {
2022 for i in to..to + count {
2023 write(it, i)?;
2024 }
2025 Ok(())
2026 }
2027 ArrOp::Reverse => {
2028 if len >= 2 {
2029 for i in 0..len {
2030 write(it, i)?;
2031 }
2032 }
2033 Ok(())
2034 }
2035 ArrOp::Sort => {
2036 for i in 0..len {
2037 write(it, i)?;
2038 }
2039 Ok(())
2040 }
2041 }
2042}
2043
2044pub(crate) fn arr_push(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2052 let t = to_object_required(it, &t, "push")?;
2053 if let Some(o) = this_objref(&t) {
2054 if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2055 arr_check(it, &o, ArrOp::Push(a.len()))?;
2056 if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2057 for v in a {
2058 items.push(v.clone());
2059 }
2060 return Ok(Value::Number(items.len() as f64));
2061 }
2062 }
2063 }
2064 let lv = it.get_property(&t, "length")?;
2065 let mut len = to_length_u64_checked(it, &lv)?;
2066 if len + (a.len() as u64) > MAX_SAFE_INT_U64 {
2067 return Err(it.type_error("Invalid array length"));
2068 }
2069 for v in a {
2070 put_prop_strict(it, &t, &len.to_string(), v.clone())?;
2071 len += 1;
2072 }
2073 put_prop_strict(it, &t, "length", Value::Number(len as f64))?;
2074 Ok(Value::Number(len as f64))
2075}
2076pub(crate) fn arr_pop(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2077 let t = to_object_required(it, &t, "pop")?;
2078 if let Some(o) = this_objref(&t) {
2079 if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2080 arr_check(it, &o, ArrOp::Pop)?;
2081 let popped = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2082 Some((items.pop().unwrap_or(Value::Undefined), items.len()))
2083 } else {
2084 None
2085 };
2086 if let Some((v, n)) = popped {
2087 move_holes(&o, |m| m.truncate(n));
2088 return Ok(v);
2089 }
2090 }
2091 }
2092 let lv = it.get_property(&t, "length")?;
2093 let len = to_length_u64_checked(it, &lv)?;
2094 if len == 0 {
2095 put_prop_strict(it, &t, "length", Value::Number(0.0))?;
2096 return Ok(Value::Undefined);
2097 }
2098 let new_len = len - 1;
2099 let index_str = new_len.to_string();
2100 let val = if has_array_elem(it, &t, &index_str)? {
2101 get_array_elem(it, &t, &index_str)?
2102 } else {
2103 Value::Undefined
2104 };
2105 del_prop_strict(it, &t, &index_str)?;
2106 put_prop_strict(it, &t, "length", Value::Number(new_len as f64))?;
2107 Ok(val)
2108}
2109pub(crate) fn arr_shift(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2110 let t = to_object_required(it, &t, "shift")?;
2111 if let Some(o) = this_objref(&t) {
2112 if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2113 arr_check(it, &o, ArrOp::Shift)?;
2114 let shifted = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2115 Some(if items.is_empty() { None } else { Some(items.remove(0)) })
2116 } else {
2117 None
2118 };
2119 match shifted {
2120 Some(None) => return Ok(Value::Undefined),
2121 Some(Some(v)) => {
2122 move_holes(&o, |m| {
2123 if !m.is_empty() {
2124 m.remove(0);
2125 }
2126 });
2127 return Ok(v);
2128 }
2129 None => {}
2130 }
2131 }
2132 }
2133 let lv = it.get_property(&t, "length")?;
2134 let len = to_length_u64_checked(it, &lv)?;
2135 if len == 0 {
2136 put_prop_strict(it, &t, "length", Value::Number(0.0))?;
2137 return Ok(Value::Undefined);
2138 }
2139 let first = if has_array_elem(it, &t, "0")? {
2140 get_array_elem(it, &t, "0")?
2141 } else {
2142 Value::Undefined
2143 };
2144 for k in 1..len {
2145 if it.tick() {
2146 return Err(Value::Undefined);
2147 }
2148 let from_key = k.to_string();
2149 let to_key = (k - 1).to_string();
2150 if has_array_elem(it, &t, &from_key)? {
2151 let v = get_array_elem(it, &t, &from_key)?;
2152 put_prop_strict(it, &t, &to_key, v)?;
2153 } else {
2154 del_prop_strict(it, &t, &to_key)?;
2155 }
2156 }
2157 del_prop_strict(it, &t, &(len - 1).to_string())?;
2158 put_prop_strict(it, &t, "length", Value::Number((len - 1) as f64))?;
2159 Ok(first)
2160}
2161pub(crate) fn arr_unshift(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2162 let t = to_object_required(it, &t, "unshift")?;
2163 if let Some(o) = this_objref(&t) {
2164 if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2165 arr_check(it, &o, ArrOp::Unshift(a.len()))?;
2166 let n = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2167 for (i, v) in a.iter().enumerate() {
2168 items.insert(i, v.clone());
2169 }
2170 Some(items.len())
2171 } else {
2172 None
2173 };
2174 if let Some(n) = n {
2175 move_holes(&o, |m| {
2176 m.splice(0..0, core::iter::repeat_n(false, a.len()));
2177 });
2178 return Ok(Value::Number(n as f64));
2179 }
2180 }
2181 }
2182 let len_val = it.get_property(&t, "length")?;
2183 let len = to_length_u64_checked(it, &len_val)?;
2184 let shift = a.len() as u64;
2185 if shift > 0 {
2186 if len + shift > MAX_SAFE_INT_U64 {
2187 return Err(it.type_error("Invalid array length"));
2188 }
2189 for k in (1..=len).rev() {
2191 if it.tick() {
2192 return Err(Value::Undefined);
2193 }
2194 let from_key = (k - 1).to_string();
2195 let to_key = (k + shift - 1).to_string();
2196 if has_array_elem(it, &t, &from_key)? {
2197 let v = get_array_elem(it, &t, &from_key)?;
2198 put_prop_strict(it, &t, &to_key, v)?;
2199 } else {
2200 del_prop_strict(it, &t, &to_key)?;
2201 }
2202 }
2203 for (i, v) in a.iter().enumerate() {
2204 put_prop_strict(it, &t, &i.to_string(), v.clone())?;
2205 }
2206 }
2207 let new_len = len + shift;
2208 put_prop_strict(it, &t, "length", Value::Number(new_len as f64))?;
2209 Ok(Value::Number(new_len as f64))
2210}
2211pub(crate) fn arr_slice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2216 let t = to_object_required(it, &t, "slice")?;
2217 if is_dense_plain_array(&t) {
2218 let len = this_items(&t).len() as u64;
2219 let start = norm_index_u64(it.num_of(&arg(a, 0))?, len) as usize;
2220 let end = if matches!(arg(a, 1), Value::Undefined) {
2221 len as usize
2222 } else {
2223 norm_index_u64(it.num_of(&arg(a, 1))?, len) as usize
2224 };
2225 let items = this_items(&t);
2227 let out = if start < end && start < items.len() {
2228 items[start..end.min(items.len())].to_vec()
2229 } else {
2230 Vec::new()
2231 };
2232 if is_typed_array(&t) {
2233 return Ok(same_kind_as(it, &t, out));
2234 }
2235 let a_obj = array_species_create(it, &t, out.len())?;
2236 return populate_array_species(it, &a_obj, out);
2237 }
2238
2239 let len_val = it.get_property(&t, "length")?;
2241 let len = to_length_u64_checked(it, &len_val)?;
2242 let k = norm_index_u64(it.num_of(&arg(a, 0))?, len);
2243 let final_idx = if matches!(arg(a, 1), Value::Undefined) {
2244 len
2245 } else {
2246 norm_index_u64(it.num_of(&arg(a, 1))?, len)
2247 };
2248 let count = final_idx.saturating_sub(k);
2249 if count > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
2250 return Err(it.range_error("Invalid array length"));
2251 }
2252 let count_usize = count as usize;
2253 let a_obj = array_species_create(it, &t, count_usize)?;
2254 let mut out = try_vec_with_capacity::<Value>(it, count_usize)?;
2255 let mut mask = try_vec_with_capacity::<bool>(it, count_usize)?;
2256 for idx in k..final_idx {
2257 let ks = idx.to_string();
2258 if has_array_elem(it, &t, &ks)? {
2259 out.push(get_array_elem(it, &t, &ks)?);
2260 mask.push(false);
2261 } else {
2262 out.push(Value::Undefined);
2263 mask.push(true);
2264 }
2265 }
2266 if is_typed_array(&t) {
2267 return Ok(same_kind_as(it, &t, out));
2268 }
2269 let r = populate_array_species(it, &a_obj, out)?;
2270 if mask.iter().any(|&h| h) {
2271 set_holes(&r, mask);
2272 }
2273 Ok(r)
2274}
2275pub(crate) fn arr_from_index(a: &[Value], len: usize) -> usize {
2278 from_index_u64(a, len as u64).unwrap_or(len as u64) as usize
2279}
2280fn num_arg1<'a>(it: &mut Interp, t: &Value, a: &'a [Value], buf: &'a mut Vec<Value>) -> Result<&'a [Value], Value> {
2290 if let Some(v @ Value::Object(_)) = a.get(1) {
2291 match t {
2292 Value::Undefined | Value::Null => return Err(it.type_error("Array.prototype method called on null or undefined")),
2293 Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) => return Ok(a),
2294 _ => {}
2295 }
2296 let len = if is_dense_plain_array(t) {
2297 with_array_items(t, |items| items.len() as u64).unwrap_or(0)
2298 } else {
2299 let lv = it.get_property(t, "length")?;
2300 to_length_u64_checked(it, &lv)?
2301 };
2302 if len == 0 {
2303 return Ok(a);
2304 }
2305 let n = it.num_of(v)?;
2306 *buf = a.to_vec();
2307 buf[1] = Value::Number(n);
2308 return Ok(&buf[..]);
2309 }
2310 Ok(a)
2311}
2312pub(crate) fn arr_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2313 if matches!(t, Value::Undefined | Value::Null) {
2314 return Err(it.type_error("Array.prototype method called on null or undefined"));
2315 }
2316 let mut a_buf = Vec::new();
2317 let a = num_arg1(it, &t, a, &mut a_buf)?;
2318 if let Some(r) = bytes_index_of(&t, a) {
2319 return Ok(Value::Number(r.map_or(-1.0, |i| i as f64)));
2320 }
2321 let target = arg(a, 0);
2322 if is_dense_plain_array(&t) {
2323 let found = with_array_items(&t, |items| {
2324 let from = arr_from_index(a, items.len());
2325 items
2326 .iter()
2327 .enumerate()
2328 .skip(from)
2329 .find(|(_, v)| v.strict_eq(&target))
2330 .map(|(i, _)| i)
2331 })
2332 .flatten();
2333 return Ok(Value::Number(found.map_or(-1.0, |i| i as f64)));
2334 }
2335 let len_val = it.get_property(&t, "length")?;
2337 let len = to_length_u64_checked(it, &len_val)?;
2338 let Some(start) = from_index_u64(a, len) else {
2339 return Ok(Value::Number(-1.0));
2340 };
2341 for k in start..len {
2342 let ks = k.to_string();
2343 if has_array_elem(it, &t, &ks)? {
2344 let v = get_array_elem(it, &t, &ks)?;
2345 if v.strict_eq(&target) {
2346 return Ok(Value::Number(k as f64));
2347 }
2348 }
2349 }
2350 Ok(Value::Number(-1.0))
2351}
2352pub(crate) fn arr_includes(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2357 if matches!(t, Value::Undefined | Value::Null) {
2358 return Err(it.type_error("Array.prototype method called on null or undefined"));
2359 }
2360 let mut a_buf = Vec::new();
2361 let a = num_arg1(it, &t, a, &mut a_buf)?;
2362 if !matches!(arg(a, 0), Value::Number(n) if n.is_nan()) {
2364 if let Some(r) = bytes_index_of(&t, a) {
2365 return Ok(Value::Bool(r.is_some()));
2366 }
2367 }
2368 let target = arg(a, 0);
2369 if is_dense_plain_array(&t) {
2370 let found = with_array_items(&t, |items| {
2371 let from = arr_from_index(a, items.len());
2372 items.iter().skip(from).any(|v| same_value_zero(v, &target))
2373 })
2374 .unwrap_or(false);
2375 return Ok(Value::Bool(found));
2376 }
2377 let len_val = it.get_property(&t, "length")?;
2379 let len = to_length_u64_checked(it, &len_val)?;
2380 let Some(start) = from_index_u64(a, len) else {
2381 return Ok(Value::Bool(false));
2382 };
2383 for k in start..len {
2384 let v = get_array_elem(it, &t, &k.to_string())?;
2385 if same_value_zero(&v, &target) {
2386 return Ok(Value::Bool(true));
2387 }
2388 }
2389 Ok(Value::Bool(false))
2390}
2391pub(crate) fn arr_join(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2397 if matches!(t, Value::Undefined | Value::Null) {
2398 return Err(it.type_error("Array.prototype method called on null or undefined"));
2399 }
2400 let is_array = matches!(&t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_) | ObjKind::Bytes(_)));
2401 let items = if is_array {
2402 this_items(&t)
2403 } else {
2404 array_like_items(it, &t)
2405 };
2406 let sep = if matches!(arg(a, 0), Value::Undefined) {
2407 String::from(",")
2408 } else {
2409 it.to_string_value(arg(a, 0))?
2410 };
2411 let self_id = match &t {
2416 Value::Object(o) => Rc::as_ptr(o) as *const () as usize,
2417 _ => 0,
2418 };
2419 if self_id != 0 && it.join_stack.contains(&self_id) {
2420 return Ok(Value::str(""));
2421 }
2422 let needs_calls = items.iter().any(|v| {
2423 matches!(v, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Plain | ObjKind::Function(_) | ObjKind::Array(_)))
2424 });
2425 if !needs_calls {
2426 let parts: Vec<String> = items
2427 .iter()
2428 .map(|v| match v {
2429 Value::Undefined | Value::Null => String::new(),
2430 _ => v.to_js_string(),
2431 })
2432 .collect();
2433 return Ok(Value::str(parts.join(&sep)));
2434 }
2435 it.join_stack.push(self_id);
2436 let mut parts: Vec<String> = Vec::with_capacity(items.len());
2437 let mut res = Ok(());
2438 for v in items.iter() {
2439 let part = match v {
2440 Value::Undefined | Value::Null => Ok(String::new()),
2441 Value::Object(o)
2442 if matches!(o.borrow().kind, ObjKind::Plain | ObjKind::Function(_) | ObjKind::HostRef(_)) =>
2443 {
2444 it.to_string_value(v.clone())
2445 }
2446 Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)) && o.borrow().proto.is_none() => {
2447 arr_join(it, v.clone(), &[]).map(|r| r.to_js_string())
2448 }
2449 _ => Ok(v.to_js_string()),
2450 };
2451 match part {
2452 Ok(p) => parts.push(p),
2453 Err(e) => {
2454 res = Err(e);
2455 break;
2456 }
2457 }
2458 }
2459 it.join_stack.pop();
2460 res?;
2461 Ok(Value::str(parts.join(&sep)))
2462}
2463pub(crate) fn with_array_items<R>(t: &Value, f: impl FnOnce(&[Value]) -> R) -> Option<R> {
2470 let Value::Object(o) = t else { return None };
2471 let o = unwrap_proxy_target(o);
2472 let b = o.borrow();
2473 match &b.kind {
2474 ObjKind::Array(items) => Some(f(items.as_slice())),
2475 _ => None,
2476 }
2477}
2478pub(crate) enum ArrView {
2482 Live(ObjRef, usize),
2483 Owned(Vec<Value>),
2484}
2485
2486impl ArrView {
2487 pub(crate) fn len(&self) -> usize {
2488 match self {
2489 ArrView::Live(_, n) => *n,
2490 ArrView::Owned(v) => v.len(),
2491 }
2492 }
2493 pub(crate) fn get(&self, i: usize) -> Option<Value> {
2494 match self {
2495 ArrView::Live(o, _) => match &o.borrow().kind {
2496 ObjKind::Array(items) => items.get(i).cloned(),
2497 _ => None,
2498 },
2499 ArrView::Owned(v) => v.get(i).cloned(),
2500 }
2501 }
2502}
2503
2504pub(crate) fn array_view(it: &mut Interp, t: &Value) -> ArrView {
2505 if let Value::Object(o) = t {
2506 let o = unwrap_proxy_target(o);
2507 let n = match &o.borrow().kind {
2508 ObjKind::Array(items) => Some(items.len()),
2509 _ => None,
2510 };
2511 if let Some(n) = n {
2512 return ArrView::Live(o, n);
2513 }
2514 }
2515 ArrView::Owned(generic_array_items(it, t))
2516}
2517pub(crate) fn is_real_array(t: &Value) -> bool {
2518 matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_) | ObjKind::Bytes(_)))
2519}
2520pub(crate) fn holes_of(t: &Value) -> Vec<bool> {
2523 match t {
2524 Value::Object(o) => o.borrow().hole_mask(),
2525 _ => Vec::new(),
2526 }
2527}
2528fn is_hole_at(holes: &[bool], i: usize) -> bool {
2529 holes.get(i).copied().unwrap_or(false)
2530}
2531pub(crate) fn set_holes(v: &Value, mask: Vec<bool>) {
2533 if let Value::Object(o) = v {
2534 let mut b = o.borrow_mut();
2535 if matches!(b.kind, ObjKind::Array(_)) {
2536 b.set_holes(if mask.iter().any(|&h| h) { Some(alloc::boxed::Box::new(mask)) } else { None });
2537 }
2538 }
2539}
2540pub(crate) fn without_holes(t: &Value, items: Vec<Value>) -> Vec<Value> {
2542 let h = holes_of(t);
2543 if h.is_empty() {
2544 return items;
2545 }
2546 items.into_iter().enumerate().filter(|(i, _)| !is_hole_at(&h, *i)).map(|(_, v)| v).collect()
2547}
2548fn drop_holes(o: &ObjRef) {
2550 o.borrow_mut().clear_holes();
2551}
2552fn move_holes(o: &ObjRef, f: impl FnOnce(&mut Vec<bool>)) {
2555 let Some(mut mask) = o.borrow().holes().map(<[bool]>::to_vec) else { return };
2557 f(&mut mask);
2558 set_holes(&Value::Object(o.clone()), mask);
2559}
2560fn bytes_index_of(t: &Value, a: &[Value]) -> Option<Option<usize>> {
2566 let Value::Object(o) = t else { return None };
2567 let b = o.borrow();
2568 let ObjKind::Bytes(st) = &b.kind else { return None };
2569 let from = arr_from_index(a, st.effective_len());
2570 let Value::Number(n) = arg(a, 0) else { return Some(None) };
2571 let rk = st.raw_kind();
2572 if rk <= 2 {
2573 let v = n as i64;
2575 let want = match rk {
2576 1 if (-128..=127).contains(&v) && v as f64 == n => (v as i8) as u8,
2577 0 | 2 if (0..=255).contains(&v) && v as f64 == n => v as u8,
2578 _ => return Some(None),
2579 };
2580 let buf = st.buf.borrow();
2581 let len = st.effective_len();
2582 let s = buf.get(st.off + from.min(len)..st.off + len)?;
2583 return Some(s.iter().position(|x| *x == want).map(|p| p + from));
2584 }
2585 Some((from..st.effective_len()).find(|i| st.get(*i) == Some(n)))
2586}
2587
2588pub(crate) fn generic_array_items(it: &mut Interp, t: &Value) -> Vec<Value> {
2589 if is_real_array(t) || matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_))) {
2590 this_items(t)
2591 } else {
2592 array_like_items(it, t)
2593 }
2594}
2595pub(crate) fn array_like_items(it: &mut Interp, v: &Value) -> Vec<Value> {
2598 let len = it
2599 .get_property(v, "length")
2600 .map(|l| to_length_u64(&l))
2601 .unwrap_or(0);
2602 let len = (len as usize).min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN);
2603 let mut out = Vec::with_capacity(len.min(4096));
2604 for i in 0..len {
2605 out.push(
2606 it.get_property(v, &i.to_string())
2607 .unwrap_or(Value::Undefined),
2608 );
2609 }
2610 out
2611}
2612
2613pub(crate) fn concat_push(
2620 it: &mut Interp,
2621 v: &Value,
2622 items: &mut Vec<Value>,
2623 mask: &mut Vec<bool>,
2624) -> Result<(), Value> {
2625 match v {
2626 Value::Object(_) => {
2627 let flag = it.get_property(v, "Symbol(Symbol.isConcatSpreadable)")?;
2628 let is_array = is_js_array(v);
2629 let spreadable = if matches!(flag, Value::Undefined) {
2630 is_array
2631 } else {
2632 flag.truthy()
2633 };
2634 if !spreadable {
2635 if (items.len() as u64) >= MAX_SAFE_INT_U64 {
2636 return Err(it.type_error("Invalid array length"));
2637 }
2638 items.push(v.clone());
2639 mask.push(false);
2640 } else if is_dense_plain_array(v) {
2641 let other = this_items(v);
2642 let len = other.len() as u64;
2643 if len > MAX_SAFE_INT_U64 - (items.len() as u64) {
2644 return Err(it.type_error("Invalid array length"));
2645 }
2646 if items.len() + other.len() > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN
2647 || items.try_reserve(other.len()).is_err()
2648 {
2649 return Err(it.range_error("Invalid array length"));
2650 }
2651 let added = other.len();
2652 items.extend(other);
2653 mask.extend(core::iter::repeat_n(false, added));
2654 } else {
2655 let len_val = it.get_property(v, "length")?;
2656 let len = to_length_u64_checked(it, &len_val)?;
2657 if len > MAX_SAFE_INT_U64 - (items.len() as u64) {
2658 return Err(it.type_error("Invalid array length"));
2659 }
2660 for k in 0..len {
2661 if items.len() >= crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
2662 return Err(it.range_error("Invalid array length"));
2663 }
2664 let ks = k.to_string();
2665 if has_array_elem(it, v, &ks)? {
2666 let sub = get_array_elem(it, v, &ks)?;
2667 items.push(sub);
2668 mask.push(false);
2669 } else {
2670 items.push(Value::Undefined);
2671 mask.push(true);
2672 }
2673 }
2674 }
2675 }
2676 other => {
2677 if (items.len() as u64) >= MAX_SAFE_INT_U64 {
2678 return Err(it.type_error("Invalid array length"));
2679 }
2680 items.push(other.clone());
2681 mask.push(false);
2682 }
2683 }
2684 Ok(())
2685}
2686pub(crate) fn arr_concat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2687 let obj = to_object_required(it, &t, "concat")?;
2688 let mut items = Vec::new();
2689 let mut mask: Vec<bool> = Vec::new();
2690 for v in core::iter::once(&obj).chain(a.iter()) {
2691 concat_push(it, v, &mut items, &mut mask)?;
2692 }
2693 let a_obj = array_species_create(it, &obj, 0)?;
2694 let r = populate_array_species(it, &a_obj, items)?;
2695 set_holes(&r, mask);
2696 Ok(r)
2697}
2698pub(crate) fn arr_reverse(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2699 let t = to_object_required(it, &t, "reverse")?;
2700 if let Some(o) = this_objref(&t) {
2701 let is_plain_arr = {
2702 let b = o.borrow();
2703 matches!(b.kind, ObjKind::Array(_)) && !b.props.contains_key("_ta_kind") && !b.has_any_accessor()
2704 };
2705 if is_plain_arr {
2706 arr_check(it, &o, ArrOp::Reverse)?;
2707 let n = match &o.borrow().kind {
2708 ObjKind::Array(items) => items.len(),
2709 _ => 0,
2710 };
2711 move_holes(&o, |m| {
2712 m.resize(n, false);
2713 m.reverse();
2714 });
2715 if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2716 items.reverse();
2717 }
2718 return Ok(t);
2719 }
2720 if matches!(o.borrow().kind, ObjKind::Bytes(_)) {
2721 let mut b = o.borrow_mut();
2722 if let ObjKind::Bytes(st) = &mut b.kind {
2723 let mut vals = st.values();
2724 vals.reverse();
2725 for (i, v) in vals.into_iter().enumerate() {
2726 st.set(i, v.to_number());
2727 }
2728 }
2729 return Ok(t);
2730 }
2731 }
2732 let lv = it.get_property(&t, "length")?;
2733 let len = to_length_u64_checked(it, &lv)?;
2734 let middle = len / 2;
2735 for lower in 0..middle {
2736 if it.tick() {
2737 return Err(Value::Undefined);
2738 }
2739 let upper = len - lower - 1;
2740 let lower_p = lower.to_string();
2741 let upper_p = upper.to_string();
2742 let lower_exists = has_array_elem(it, &t, &lower_p)?;
2743 let lower_val = if lower_exists {
2744 Some(get_array_elem(it, &t, &lower_p)?)
2745 } else {
2746 None
2747 };
2748 let upper_exists = has_array_elem(it, &t, &upper_p)?;
2749 let upper_val = if upper_exists {
2750 Some(get_array_elem(it, &t, &upper_p)?)
2751 } else {
2752 None
2753 };
2754 match (lower_val, upper_val) {
2755 (Some(lv_val), Some(uv_val)) => {
2756 put_prop_strict(it, &t, &lower_p, uv_val)?;
2757 put_prop_strict(it, &t, &upper_p, lv_val)?;
2758 }
2759 (None, Some(uv_val)) => {
2760 put_prop_strict(it, &t, &lower_p, uv_val)?;
2761 del_prop_strict(it, &t, &upper_p)?;
2762 }
2763 (Some(lv_val), None) => {
2764 del_prop_strict(it, &t, &lower_p)?;
2765 put_prop_strict(it, &t, &upper_p, lv_val)?;
2766 }
2767 (None, None) => {}
2768 }
2769 }
2770 Ok(t)
2771}
2772pub(crate) fn arr_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2773 if matches!(t, Value::Undefined | Value::Null) {
2774 return Err(it.type_error("Array.prototype method called on null or undefined"));
2775 }
2776 Ok(Value::str(t.to_js_string()))
2777}
2778pub(crate) fn obj_to_locale_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2783 let to_str = it.get_property(&t, "toString")?;
2784 if !matches!(&to_str, Value::Object(f) if f.borrow().is_callable()) {
2785 return Err(it.type_error("toString is not a function"));
2786 }
2787 it.call_value(&to_str, t, &[])
2788}
2789
2790pub(crate) fn arr_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2791 let t = to_object_required(it, &t, "toLocaleString")?;
2792 let lv = it.get_property(&t, "length")?;
2793 let len = to_length_u64_checked(it, &lv)?;
2794 if len > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
2795 return Err(it.range_error("Invalid array length"));
2796 }
2797 let mut parts = Vec::with_capacity(len as usize);
2798 for k in 0..len {
2799 let v = get_array_elem(it, &t, &k.to_string())?;
2800 if matches!(v, Value::Undefined | Value::Null) {
2801 parts.push(String::new());
2802 continue;
2803 }
2804 let method = it.get_property(&v, "toLocaleString")?;
2805 if !matches!(&method, Value::Object(f) if f.borrow().is_callable()) {
2806 return Err(it.type_error("toLocaleString is not a function"));
2807 }
2808 let res = it.call_value(&method, v, a)?;
2809 parts.push(it.to_string_value(res)?);
2810 }
2811 Ok(Value::str(parts.join(",")))
2812}
2813pub(crate) fn arr_map_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2817 if matches!(t, Value::Undefined | Value::Null) {
2818 return Err(it.type_error("Array.prototype method called on null or undefined"));
2819 }
2820 let items = array_view(it, &t);
2821 let f = arg(a, 0);
2822 let this_arg = arg(a, 1);
2823 let holes = holes_of(&t);
2824 let mut out = Vec::with_capacity(items.len());
2825 for i in 0..items.len() {
2826 let v = match items.get(i) {
2827 Some(v) if !is_hole_at(&holes, i) => v,
2828 _ => {
2829 out.push(Value::Undefined);
2830 continue;
2831 }
2832 };
2833 let r = it.call_value(
2834 &f,
2835 this_arg.clone(),
2836 &[v.clone(), Value::Number(i as f64), t.clone()],
2837 )?;
2838 out.push(r);
2839 }
2840 if is_typed_array(&t) {
2841 return Ok(same_kind_as(it, &t, out));
2842 }
2843 let a_obj = array_species_create(it, &t, items.len())?;
2844 let r = populate_array_species(it, &a_obj, out)?;
2845 set_holes(&r, holes);
2846 Ok(r)
2847}
2848pub(crate) fn arr_filter_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2849 if matches!(t, Value::Undefined | Value::Null) {
2850 return Err(it.type_error("Array.prototype method called on null or undefined"));
2851 }
2852 let items = array_view(it, &t);
2853 let f = arg(a, 0);
2854 let this_arg = arg(a, 1);
2855 let mut out = Vec::new();
2856 let holes = holes_of(&t);
2857 for i in 0..items.len() {
2858 let v = match items.get(i) {
2859 Some(v) if !is_hole_at(&holes, i) => v,
2860 _ => continue,
2861 };
2862 if it
2863 .call_value(
2864 &f,
2865 this_arg.clone(),
2866 &[v.clone(), Value::Number(i as f64), t.clone()],
2867 )?
2868 .truthy()
2869 {
2870 out.push(v.clone());
2871 }
2872 }
2873 if is_typed_array(&t) {
2874 return Ok(same_kind_as(it, &t, out));
2875 }
2876 let a_obj = array_species_create(it, &t, 0)?;
2877 populate_array_species(it, &a_obj, out)
2878}
2879pub(crate) fn arr_for_each_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2884 if matches!(t, Value::Undefined | Value::Null) {
2885 return Err(it.type_error("Array.prototype method called on null or undefined"));
2886 }
2887 let items = array_view(it, &t);
2888 let f = arg(a, 0);
2889 let this_arg = arg(a, 1);
2890 let holes = holes_of(&t);
2891 for i in 0..items.len() {
2892 let v = match items.get(i) {
2893 Some(v) if !is_hole_at(&holes, i) => v,
2894 _ => continue,
2895 };
2896 it.call_value(
2897 &f,
2898 this_arg.clone(),
2899 &[v.clone(), Value::Number(i as f64), t.clone()],
2900 )?;
2901 }
2902 Ok(Value::Undefined)
2903}
2904pub(crate) fn arr_reduce_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2908 if matches!(t, Value::Undefined | Value::Null) {
2909 return Err(it.type_error("Array.prototype method called on null or undefined"));
2910 }
2911 let items = generic_array_items(it, &t);
2912 let f = arg(a, 0);
2913 let holes = holes_of(&t);
2914 let mut idx = 0;
2915 let mut acc = if a.len() >= 2 {
2916 arg(a, 1)
2917 } else {
2918 while is_hole_at(&holes, idx) {
2919 idx += 1;
2920 }
2921 if idx >= items.len() {
2922 return Err(it.type_error("Reduce of empty array with no initial value"));
2923 }
2924 idx += 1;
2925 items[idx - 1].clone()
2926 };
2927 while idx < items.len() {
2928 if is_hole_at(&holes, idx) {
2929 idx += 1;
2930 continue;
2931 }
2932 acc = it.call_value(
2933 &f,
2934 Value::Undefined,
2935 &[
2936 acc,
2937 items[idx].clone(),
2938 Value::Number(idx as f64),
2939 t.clone(),
2940 ],
2941 )?;
2942 idx += 1;
2943 }
2944 Ok(acc)
2945}
2946fn elem_at(it: &mut Interp, t: &Value, k: u64) -> Result<Value, Value> {
2948 if let Value::Object(o) = t {
2949 let b = o.borrow();
2950 if let ObjKind::Array(items) = &b.kind {
2951 let i = k as usize;
2952 if i < items.len() && !b.is_hole(i) && !b.has_any_accessor() {
2953 return Ok(items[i].clone());
2954 }
2955 }
2956 }
2957 get_array_elem(it, t, &k.to_string())
2958}
2959
2960fn find_core(it: &mut Interp, t: Value, a: &[Value], rev: bool, want_index: bool) -> Result<Value, Value> {
2963 if matches!(t, Value::Undefined | Value::Null) {
2964 return Err(it.type_error("Array.prototype method called on null or undefined"));
2965 }
2966 let len_val = it.get_property(&t, "length")?;
2967 let len = to_length_u64_checked(it, &len_val)?;
2968 let f = arg(a, 0);
2969 if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
2970 return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(&f))));
2971 }
2972 let this_arg = arg(a, 1);
2973 let mut n = 0u64;
2974 while n < len {
2975 let k = if rev { len - 1 - n } else { n };
2976 n += 1;
2977 let v = elem_at(it, &t, k)?;
2978 if it.call_value(&f, this_arg.clone(), &[v.clone(), Value::Number(k as f64), t.clone()])?.truthy() {
2979 return Ok(if want_index { Value::Number(k as f64) } else { v });
2980 }
2981 }
2982 Ok(if want_index { Value::Number(-1.0) } else { Value::Undefined })
2983}
2984pub(crate) fn arr_find(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2985 find_core(it, t, a, false, false)
2986}
2987pub(crate) fn arr_find_index(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2988 find_core(it, t, a, false, true)
2989}
2990pub(crate) fn arr_some_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2991 if matches!(t, Value::Undefined | Value::Null) {
2992 return Err(it.type_error("Array.prototype method called on null or undefined"));
2993 }
2994 let items = generic_array_items(it, &t);
2995 let f = arg(a, 0);
2996 let this_arg = arg(a, 1);
2997 let holes = holes_of(&t);
2998 for (i, v) in items.iter().enumerate() {
2999 if is_hole_at(&holes, i) {
3000 continue;
3001 }
3002 if it
3003 .call_value(
3004 &f,
3005 this_arg.clone(),
3006 &[v.clone(), Value::Number(i as f64), t.clone()],
3007 )?
3008 .truthy()
3009 {
3010 return Ok(Value::Bool(true));
3011 }
3012 }
3013 Ok(Value::Bool(false))
3014}
3015pub(crate) fn arr_every_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3016 if matches!(t, Value::Undefined | Value::Null) {
3017 return Err(it.type_error("Array.prototype method called on null or undefined"));
3018 }
3019 let items = generic_array_items(it, &t);
3020 let f = arg(a, 0);
3021 let this_arg = arg(a, 1);
3022 let holes = holes_of(&t);
3023 for (i, v) in items.iter().enumerate() {
3024 if is_hole_at(&holes, i) {
3025 continue;
3026 }
3027 if !it
3028 .call_value(
3029 &f,
3030 this_arg.clone(),
3031 &[v.clone(), Value::Number(i as f64), t.clone()],
3032 )?
3033 .truthy()
3034 {
3035 return Ok(Value::Bool(false));
3036 }
3037 }
3038 Ok(Value::Bool(true))
3039}
3040fn hof_is_bytes(t: &Value) -> bool {
3046 matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)))
3047}
3048
3049fn hof_begin_obj_raw(it: &mut Interp, t: &Value, cb: &Value, name: &str) -> Result<(Value, u64), Value> {
3051 let obj = to_object_required(it, t, name)?;
3052 let lv = it.get_property(&obj, "length")?;
3053 let n = it.num_of(&lv)?;
3054 let len = to_length_u64(&Value::Number(n));
3055 if !matches!(cb, Value::Object(f) if f.borrow().is_callable()) {
3056 return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(cb))));
3057 }
3058 Ok((obj, len))
3059}
3060
3061fn hof_begin_obj(it: &mut Interp, t: &Value, cb: &Value, name: &str) -> Result<(Value, u64), Value> {
3063 let (obj, len) = hof_begin_obj_raw(it, t, cb, name)?;
3064 Ok((obj, len.min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64)))
3065}
3066
3067fn describe_for_error(v: &Value) -> String {
3068 match v {
3069 Value::Object(_) => String::from("#<Object>"),
3070 Value::Str(s) => alloc::format!("\"{}\"", s),
3071 other => other.to_js_string(),
3072 }
3073}
3074
3075#[inline]
3077fn hof_elem(it: &mut Interp, o: &Value, k: u64) -> Result<Option<Value>, Value> {
3078 if let Value::Object(ob) = o {
3079 let b = ob.borrow();
3080 if let ObjKind::Array(items) = &b.kind {
3081 let i = k as usize;
3082 if i < items.len() && !b.is_hole(i) && !b.has_rare_props() {
3083 return Ok(Some(items[i].clone()));
3084 }
3085 }
3086 }
3087 let key = k.to_string();
3088 if has_array_elem(it, o, &key)? {
3089 Ok(Some(get_array_elem(it, o, &key)?))
3090 } else {
3091 Ok(None)
3092 }
3093}
3094
3095pub(crate) fn arr_for_each_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3096 if hof_is_bytes(&t) {
3097 return arr_for_each_legacy(it, t, a);
3098 }
3099 let f = arg(a, 0);
3100 let (t, len) = hof_begin_obj(it, &t, &f, "forEach")?;
3101 let this_arg = arg(a, 1);
3102 for k in 0..len {
3103 if let Some(v) = hof_elem(it, &t, k)? {
3104 it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?;
3105 }
3106 }
3107 Ok(Value::Undefined)
3108}
3109
3110pub(crate) fn arr_some_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3111 if hof_is_bytes(&t) {
3112 return arr_some_legacy(it, t, a);
3113 }
3114 let f = arg(a, 0);
3115 let (t, len) = hof_begin_obj(it, &t, &f, "some")?;
3116 let this_arg = arg(a, 1);
3117 for k in 0..len {
3118 if let Some(v) = hof_elem(it, &t, k)? {
3119 if it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?.truthy() {
3120 return Ok(Value::Bool(true));
3121 }
3122 }
3123 }
3124 Ok(Value::Bool(false))
3125}
3126
3127pub(crate) fn arr_every_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3128 if hof_is_bytes(&t) {
3129 return arr_every_legacy(it, t, a);
3130 }
3131 let f = arg(a, 0);
3132 let (t, len) = hof_begin_obj(it, &t, &f, "every")?;
3133 let this_arg = arg(a, 1);
3134 for k in 0..len {
3135 if let Some(v) = hof_elem(it, &t, k)? {
3136 if !it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?.truthy() {
3137 return Ok(Value::Bool(false));
3138 }
3139 }
3140 }
3141 Ok(Value::Bool(true))
3142}
3143
3144fn hof_put(it: &mut Interp, target: &Value, idx: u64, v: Value) -> Result<(), Value> {
3146 if let Value::Object(o) = target {
3147 let mut b = o.borrow_mut();
3148 let i = idx as usize;
3149 let plain = !b.has_rare_props() && !b.is_frozen() && !b.is_sealed() && !b.is_non_extensible();
3150 if plain {
3151 let mut grown = false;
3152 if let ObjKind::Array(items) = &mut b.kind {
3153 if i == items.len() {
3154 items.push(v.clone());
3155 grown = true;
3156 } else if i < items.len() {
3157 items[i] = v.clone();
3158 grown = true;
3159 }
3160 }
3161 if grown {
3162 return Ok(());
3163 }
3164 }
3165 }
3166 super::object_array::create_data_property_or_throw(it, target, &idx.to_string(), v)
3167}
3168
3169pub(crate) fn arr_map_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3170 if hof_is_bytes(&t) {
3171 return arr_map_legacy(it, t, a);
3172 }
3173 let f = arg(a, 0);
3174 let (t, raw_len) = hof_begin_obj_raw(it, &t, &f, "map")?;
3175 let this_arg = arg(a, 1);
3176 let out = if raw_len > u32::MAX as u64 {
3177 let is_arr = super::object_array::is_array_value(it, &t)?;
3178 let custom_species = if is_arr {
3179 let ctor = it.get_property(&t, "constructor")?;
3180 if let Value::Object(co) = &ctor {
3181 let sp = it.get_property(&Value::Object(co.clone()), "Symbol(Symbol.species)")?;
3182 match &sp {
3183 Value::Undefined | Value::Null => None,
3184 Value::Object(so) if so.borrow().is_callable() => Some(sp),
3185 _ => return Err(it.type_error("Symbol.species is not a constructor")),
3186 }
3187 } else if matches!(ctor, Value::Undefined) {
3188 None
3189 } else {
3190 return Err(it.type_error("Array constructor is not an object"));
3191 }
3192 } else {
3193 None
3194 };
3195 match custom_species {
3196 Some(sp) => it.construct_value(&sp, &[Value::Number(raw_len as f64)])?,
3197 None => return Err(it.range_error("Invalid array length")),
3198 }
3199 } else {
3200 array_species_create(it, &t, raw_len as usize)?
3201 };
3202 let len = raw_len.min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64);
3203 let fast = match &out {
3205 Value::Object(o) => {
3206 let mut b = o.borrow_mut();
3207 let ok = matches!(b.kind, ObjKind::Array(_))
3208 && !b.has_rare_props()
3209 && !b.is_frozen()
3210 && !b.is_sealed()
3211 && !b.is_non_extensible();
3212 if ok {
3213 let old = b.hole_mask();
3214 let n = match &mut b.kind {
3215 ObjKind::Array(items) => {
3216 let n = items.len();
3217 if (n as u64) < len {
3218 items.resize(len as usize, Value::Undefined);
3219 }
3220 n
3221 }
3222 _ => 0,
3223 };
3224 if (n as u64) < len {
3225 let mut m = old;
3226 m.resize(len as usize, false);
3227 for h in m.iter_mut().skip(n) {
3228 *h = true;
3229 }
3230 b.set_holes(Some(alloc::boxed::Box::new(m)));
3231 }
3232 }
3233 ok
3234 }
3235 _ => false,
3236 };
3237 for k in 0..len {
3238 if let Some(v) = hof_elem(it, &t, k)? {
3239 let r = it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?;
3240 let mut done = false;
3241 if fast {
3242 if let Value::Object(o) = &out {
3243 let mut b = o.borrow_mut();
3244 let i = k as usize;
3245 if let ObjKind::Array(items) = &mut b.kind {
3246 if i < items.len() {
3247 items[i] = r.clone();
3248 done = true;
3249 }
3250 }
3251 if done {
3252 b.clear_hole(i);
3253 }
3254 }
3255 }
3256 if !done {
3257 hof_put(it, &out, k, r)?;
3258 }
3259 }
3260 }
3261 if !fast {
3262 it.put_value(&out, "length", Value::Number(len as f64))?;
3263 }
3264 Ok(out)
3265}
3266
3267pub(crate) fn arr_filter_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3268 if hof_is_bytes(&t) {
3269 return arr_filter_legacy(it, t, a);
3270 }
3271 let f = arg(a, 0);
3272 let (t, len) = hof_begin_obj(it, &t, &f, "filter")?;
3273 let this_arg = arg(a, 1);
3274 let out = array_species_create(it, &t, 0)?;
3275 let mut to = 0u64;
3276 for k in 0..len {
3277 if let Some(v) = hof_elem(it, &t, k)? {
3278 if it.call_value(&f, this_arg.clone(), &[v.clone(), Value::Number(k as f64), t.clone()])?.truthy() {
3279 hof_put(it, &out, to, v)?;
3280 to += 1;
3281 }
3282 }
3283 }
3284 Ok(out)
3285}
3286
3287pub(crate) fn arr_reduce_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3288 if hof_is_bytes(&t) {
3289 return arr_reduce_legacy(it, t, a);
3290 }
3291 let f = arg(a, 0);
3292 let (t, len) = hof_begin_obj(it, &t, &f, "reduce")?;
3293 let mut k = 0u64;
3294 let mut acc = if a.len() >= 2 {
3295 arg(a, 1)
3296 } else {
3297 let mut init = None;
3298 while k < len {
3299 let e = hof_elem(it, &t, k)?;
3300 k += 1;
3301 if let Some(v) = e {
3302 init = Some(v);
3303 break;
3304 }
3305 }
3306 match init {
3307 Some(v) => v,
3308 None => return Err(it.type_error("Reduce of empty array with no initial value")),
3309 }
3310 };
3311 while k < len {
3312 if let Some(v) = hof_elem(it, &t, k)? {
3313 acc = it.call_value(&f, Value::Undefined, &[acc, v, Value::Number(k as f64), t.clone()])?;
3314 }
3315 k += 1;
3316 }
3317 Ok(acc)
3318}
3319pub(crate) fn sort_excluding_undefined(
3325 it: &mut Interp,
3326 mut items: alloc::vec::Vec<Value>,
3327 cmp: &Value,
3328) -> Result<alloc::vec::Vec<Value>, Value> {
3329 let undefined_count = items.iter().filter(|v| matches!(v, Value::Undefined)).count();
3333 items.retain(|v| !matches!(v, Value::Undefined));
3334 let n = items.len();
3335 let keys: Option<alloc::vec::Vec<String>> = if matches!(cmp, Value::Undefined) {
3336 let mut ks = alloc::vec::Vec::with_capacity(items.len());
3337 for v in &items {
3338 ks.push(it.to_string_value(v.clone())?);
3339 }
3340 Some(ks)
3341 } else {
3342 None
3343 };
3344 let greater = |it: &mut Interp, a: usize, b: usize| -> Result<bool, Value> {
3346 match &keys {
3347 Some(k) => Ok(k[a] > k[b]),
3348 None => {
3349 let v = it.call_value(cmp, Value::Undefined, &[items[a].clone(), items[b].clone()])?;
3350 let n = it.num_of(&v)?;
3351 Ok(n > 0.0)
3352 }
3353 }
3354 };
3355 let mut idx: alloc::vec::Vec<usize> = (0..n).collect();
3356 let mut buf: alloc::vec::Vec<usize> = alloc::vec![0; n];
3357 let mut width = 1;
3358 while width < n {
3359 let mut lo = 0;
3360 while lo < n {
3361 let mid = (lo + width).min(n);
3362 let hi = (lo + 2 * width).min(n);
3363 let (mut l, mut r, mut k) = (lo, mid, lo);
3364 while l < mid && r < hi {
3365 if greater(it, idx[l], idx[r])? {
3366 buf[k] = idx[r];
3367 r += 1;
3368 } else {
3369 buf[k] = idx[l];
3370 l += 1;
3371 }
3372 k += 1;
3373 }
3374 buf[k..k + (mid - l)].copy_from_slice(&idx[l..mid]);
3375 k += mid - l;
3376 buf[k..k + (hi - r)].copy_from_slice(&idx[r..hi]);
3377 lo += 2 * width;
3378 }
3379 core::mem::swap(&mut idx, &mut buf);
3380 width *= 2;
3381 }
3382 let mut out: alloc::vec::Vec<Value> = idx.into_iter().map(|i| items[i].clone()).collect();
3383 for _ in 0..undefined_count {
3384 out.push(Value::Undefined);
3385 }
3386 Ok(out)
3387}
3388pub(crate) fn put_prop_strict(it: &mut Interp, obj: &Value, key: &str, val: Value) -> Result<(), Value> {
3389 if !it.set_property_inner(obj, key, None, val)? {
3390 return Err(it.type_error(alloc::format!("Cannot assign to read only property '{}'", key)));
3391 }
3392 Ok(())
3393}
3394
3395fn del_prop_strict(it: &mut Interp, obj: &Value, key: &str) -> Result<(), Value> {
3396 if !it.delete_property(obj, key)?.truthy() {
3397 return Err(it.type_error(alloc::format!("Cannot delete property '{}'", key)));
3398 }
3399 Ok(())
3400}
3401
3402pub(crate) fn arr_sort(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3403 if matches!(t, Value::Undefined | Value::Null) {
3404 return Err(it.type_error("Array.prototype method called on null or undefined"));
3405 }
3406 let cmp = arg(a, 0);
3407 if !matches!(cmp, Value::Undefined) && !matches!(&cmp, Value::Object(f) if f.borrow().is_callable()) {
3408 return Err(it.type_error("The comparison function must be either a function or undefined"));
3409 }
3410 let obj = if matches!(&t, Value::Object(_)) {
3411 t.clone()
3412 } else {
3413 super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3414 };
3415 if is_dense_plain_array(&obj) && matches!(&obj, Value::Object(o) if o.borrow().proto.is_none()) {
3416 let items = this_items(&obj);
3417 let items = sort_excluding_undefined(it, items, &cmp)?;
3418 if let Some(o) = this_objref(&obj) {
3419 arr_check(it, &o, ArrOp::Sort)?;
3420 if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3421 *slot = items;
3422 }
3423 }
3424 return Ok(obj);
3425 }
3426 if let Some(o) = this_objref(&obj) {
3427 if matches!(&o.borrow().kind, ObjKind::Bytes(_)) {
3428 let items = this_items(&obj);
3429 let sorted = sort_excluding_undefined(it, items, &cmp)?;
3430 arr_check(it, &o, ArrOp::Sort)?;
3431 if let ObjKind::Bytes(st) = &mut o.borrow_mut().kind {
3432 for (i, v) in sorted.into_iter().enumerate() {
3433 st.set_value(i, &v);
3434 }
3435 }
3436 return Ok(obj);
3437 }
3438 }
3439 let len_val = it.get_property(&obj, "length")?;
3440 let len = to_length_u64_checked(it, &len_val)?;
3441 let max_len = (crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64).min(len);
3442 let mut items = Vec::new();
3443 for k in 0..max_len {
3444 let ks = k.to_string();
3445 if has_array_elem(it, &obj, &ks)? {
3446 items.push(get_array_elem(it, &obj, &ks)?);
3447 }
3448 }
3449 let item_count = items.len();
3450 let sorted = sort_excluding_undefined(it, items, &cmp)?;
3451 if let Some(o) = this_objref(&obj) {
3452 let is_plain_arr = {
3453 let b = o.borrow();
3454 matches!(&b.kind, ObjKind::Array(_))
3455 && !b.props.contains_key("_ta_kind")
3456 && !b.has_rare_props()
3457 && b.proto.is_none()
3458 };
3459 let is_bytes = matches!(&o.borrow().kind, ObjKind::Bytes(_));
3460 if is_plain_arr {
3461 arr_check(it, &o, ArrOp::Sort)?;
3462 let n_holes = (max_len as usize).saturating_sub(item_count);
3463 let mut full = sorted;
3464 full.extend(core::iter::repeat_n(Value::Undefined, n_holes));
3465 drop_holes(&o);
3466 if n_holes > 0 {
3467 let mut mask = alloc::vec![false; item_count];
3468 mask.extend(core::iter::repeat_n(true, n_holes));
3469 set_holes(&obj, mask);
3470 }
3471 if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3472 *slot = full;
3473 }
3474 return Ok(obj);
3475 }
3476 if is_bytes {
3477 arr_check(it, &o, ArrOp::Sort)?;
3478 if let ObjKind::Bytes(st) = &mut o.borrow_mut().kind {
3479 for (i, v) in sorted.into_iter().enumerate() {
3480 st.set(i, v.to_number());
3481 }
3482 }
3483 return Ok(obj);
3484 }
3485 }
3486 for (i, v) in sorted.into_iter().enumerate() {
3487 put_prop_strict(it, &obj, &i.to_string(), v)?;
3488 }
3489 for k in (item_count as u64)..max_len {
3490 del_prop_strict(it, &obj, &k.to_string())?;
3491 }
3492 Ok(obj)
3493}
3494pub(crate) fn arr_fill(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3498 if matches!(t, Value::Undefined | Value::Null) {
3499 return Err(it.type_error("Array.prototype method called on null or undefined"));
3500 }
3501 if let Some(o) = this_objref(&t) {
3502 let cur_len = match &o.borrow().kind {
3503 ObjKind::Array(items) => items.len(),
3504 _ => 0,
3505 };
3506 {
3507 let len = cur_len as i64;
3508 let start = norm_index(it.num_of(&arg(a, 1))?, len, 0).max(0) as usize;
3509 let end = if matches!(arg(a, 2), Value::Undefined) {
3510 len
3511 } else {
3512 norm_index(it.num_of(&arg(a, 2))?, len, len)
3513 }
3514 .max(0) as usize;
3515 arr_check(it, &o, ArrOp::Fill(start, end.min(cur_len)))?;
3516 }
3517 if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
3518 let v = arg(a, 0);
3519 let len = items.len() as i64;
3520 let start = norm_index(it.num_of(&arg(a, 1))?, len, 0).max(0) as usize;
3521 let end = if matches!(arg(a, 2), Value::Undefined) {
3522 len
3523 } else {
3524 norm_index(it.num_of(&arg(a, 2))?, len, len)
3525 }
3526 .max(0) as usize;
3527 let end = end.min(items.len());
3528 for slot in items.iter_mut().take(end).skip(start) {
3529 *slot = v.clone();
3530 }
3531 }
3532 }
3533 Ok(t)
3534}
3535pub(crate) fn arr_splice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3536 if matches!(t, Value::Undefined | Value::Null) {
3537 return Err(it.type_error("Array.prototype method called on null or undefined"));
3538 }
3539 let obj = if matches!(&t, Value::Object(_)) {
3540 t.clone()
3541 } else {
3542 super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3543 };
3544 if is_direct_array(&obj) {
3545 let o = match this_objref(&obj) {
3546 Some(o) => o,
3547 None => return Ok(Value::Object(Obj::array(alloc::vec![]))),
3548 };
3549 let mut items = if let ObjKind::Array(v) = &o.borrow().kind {
3550 v.clone()
3551 } else {
3552 return Ok(Value::Object(Obj::array(alloc::vec![])));
3553 };
3554 let len_u64 = items.len() as u64;
3555 let start = norm_index_u64(it.num_of(&arg(a, 0))?, len_u64) as usize;
3556 let delete_count = if a.is_empty() {
3557 0
3558 } else if a.len() < 2 {
3559 items.len() - start
3560 } else {
3561 let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
3562 if dc <= 0.0 {
3563 0
3564 } else if dc == f64::INFINITY || dc >= ((items.len() - start) as f64) {
3565 items.len() - start
3566 } else {
3567 dc as usize
3568 }
3569 };
3570 let insert: alloc::vec::Vec<Value> = a.iter().skip(2).cloned().collect();
3571 let n_insert = insert.len();
3572 arr_check(it, &o, ArrOp::Splice(start, delete_count, n_insert))?;
3573 let h = holes_of(&obj);
3574 let mut removed = Vec::with_capacity(delete_count);
3575 let mut removed_mask = Vec::new();
3576 for (idx, item) in items.iter().enumerate().skip(start).take(delete_count) {
3577 if is_hole_at(&h, idx) {
3578 let ks = idx.to_string();
3579 if has_array_elem(it, &obj, &ks)? {
3580 removed.push(get_array_elem(it, &obj, &ks)?);
3581 removed_mask.push(false);
3582 } else {
3583 removed.push(Value::Undefined);
3584 removed_mask.push(true);
3585 }
3586 } else {
3587 removed.push(item.clone());
3588 removed_mask.push(false);
3589 }
3590 }
3591 items.drain(start..start + delete_count);
3592 for (i, v) in insert.into_iter().enumerate() {
3593 items.insert(start + i, v);
3594 }
3595 let new_mask: Vec<bool> = if h.is_empty() {
3596 Vec::new()
3597 } else {
3598 let old_len = items.len() + delete_count - n_insert;
3599 let mut m: Vec<bool> = (0..start).map(|i| is_hole_at(&h, i)).collect();
3600 m.extend(core::iter::repeat_n(false, n_insert));
3601 m.extend((start + delete_count..old_len).map(|i| is_hole_at(&h, i)));
3602 m
3603 };
3604 drop_holes(&o);
3605 if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3606 *slot = items;
3607 }
3608 if !new_mask.is_empty() {
3609 set_holes(&obj, new_mask);
3610 }
3611 let a_obj = array_species_create(it, &obj, removed.len())?;
3612 let r = populate_array_species(it, &a_obj, removed)?;
3613 if removed_mask.iter().any(|&x| x) {
3614 set_holes(&r, removed_mask);
3615 }
3616 return Ok(r);
3617 }
3618
3619 let len_val = it.get_property(&obj, "length")?;
3621 let len = to_length_u64_checked(it, &len_val)?;
3622 let actual_start = norm_index_u64(it.num_of(&arg(a, 0))?, len);
3623 let insert_count = a.len().saturating_sub(2) as u64;
3624 let actual_delete_count = if a.is_empty() {
3625 0
3626 } else if a.len() < 2 {
3627 len - actual_start
3628 } else {
3629 let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
3630 if dc <= 0.0 {
3631 0
3632 } else if dc == f64::INFINITY || dc >= ((len - actual_start) as f64) {
3633 len - actual_start
3634 } else {
3635 dc as u64
3636 }
3637 };
3638 if len + insert_count - actual_delete_count > MAX_SAFE_INT_U64 {
3639 return Err(it.type_error("Invalid array length"));
3640 }
3641 if actual_delete_count > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
3642 return Err(it.range_error("Invalid array length"));
3643 }
3644 let del_usize = actual_delete_count as usize;
3645 let a_obj = array_species_create(it, &obj, del_usize)?;
3646 let mut removed = try_vec_with_capacity::<Value>(it, del_usize)?;
3647 let mut removed_mask = try_vec_with_capacity::<bool>(it, del_usize)?;
3648 for k in 0..actual_delete_count {
3649 let ks = (actual_start + k).to_string();
3650 if has_array_elem(it, &obj, &ks)? {
3651 removed.push(get_array_elem(it, &obj, &ks)?);
3652 removed_mask.push(false);
3653 } else {
3654 removed.push(Value::Undefined);
3655 removed_mask.push(true);
3656 }
3657 }
3658 if insert_count < actual_delete_count {
3659 for k in actual_start..(len - actual_delete_count) {
3660 let from = (k + actual_delete_count).to_string();
3661 let to = (k + insert_count).to_string();
3662 if has_array_elem(it, &obj, &from)? {
3663 let fv = get_array_elem(it, &obj, &from)?;
3664 put_prop_strict(it, &obj, &to, fv)?;
3665 } else {
3666 del_prop_strict(it, &obj, &to)?;
3667 }
3668 }
3669 let mut k = len;
3670 let target_len = len - actual_delete_count + insert_count;
3671 while k > target_len {
3672 k -= 1;
3673 del_prop_strict(it, &obj, &k.to_string())?;
3674 }
3675 } else if insert_count > actual_delete_count {
3676 let mut k = len - actual_delete_count;
3677 while k > actual_start {
3678 k -= 1;
3679 let from = (k + actual_delete_count).to_string();
3680 let to = (k + insert_count).to_string();
3681 if has_array_elem(it, &obj, &from)? {
3682 let fv = get_array_elem(it, &obj, &from)?;
3683 put_prop_strict(it, &obj, &to, fv)?;
3684 } else {
3685 del_prop_strict(it, &obj, &to)?;
3686 }
3687 }
3688 }
3689 for (i, item) in a.iter().skip(2).enumerate() {
3690 put_prop_strict(it, &obj, &(actual_start + (i as u64)).to_string(), item.clone())?;
3691 }
3692 let new_len = len - actual_delete_count + insert_count;
3693 put_prop_strict(it, &obj, "length", Value::Number(new_len as f64))?;
3694 let r = populate_array_species(it, &a_obj, removed)?;
3695 if removed_mask.iter().any(|&x| x) {
3696 set_holes(&r, removed_mask);
3697 }
3698 Ok(r)
3699}
3700
3701pub(crate) fn arr_last_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3709 if matches!(t, Value::Undefined | Value::Null) {
3710 return Err(it.type_error("Array.prototype method called on null or undefined"));
3711 }
3712 let mut a_buf = Vec::new();
3713 let a = num_arg1(it, &t, a, &mut a_buf)?;
3714 let target = arg(a, 0);
3715 if is_dense_plain_array(&t) {
3716 let found = with_array_items(&t, |items| {
3717 let len = items.len() as i128;
3718 if len == 0 {
3719 return None;
3720 }
3721 let start = if a.len() < 2 {
3722 len - 1
3723 } else {
3724 let n = to_integer_or_infinity(arg(a, 1).to_number());
3725 if n == f64::NEG_INFINITY {
3726 return None;
3727 } else if n == f64::INFINITY {
3728 len - 1
3729 } else if n < 0.0 {
3730 let s = len + (n as i128);
3731 if s < 0 {
3732 return None;
3733 }
3734 s
3735 } else {
3736 (n as i128).min(len - 1)
3737 }
3738 };
3739 (0..=start as usize).rev().find(|&i| items.get(i).is_some_and(|v| v.strict_eq(&target)))
3740 })
3741 .flatten();
3742 return Ok(Value::Number(found.map_or(-1.0, |i| i as f64)));
3743 }
3744
3745 let len_val = it.get_property(&t, "length")?;
3746 let len = to_length_u64_checked(it, &len_val)?;
3747 if len == 0 {
3748 return Ok(Value::Number(-1.0));
3749 }
3750 let len_i128 = len as i128;
3751 let mut k = if a.len() < 2 {
3752 len_i128 - 1
3753 } else {
3754 let raw = arg(a, 1);
3756 let n = if matches!(&t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_))) {
3757 to_integer_or_infinity(raw.to_number())
3758 } else {
3759 to_integer_or_infinity(it.num_of(&raw)?)
3760 };
3761 if n == f64::NEG_INFINITY {
3762 return Ok(Value::Number(-1.0));
3763 } else if n == f64::INFINITY {
3764 len_i128 - 1
3765 } else if n < 0.0 {
3766 len_i128 + (n as i128)
3767 } else {
3768 (n as i128).min(len_i128 - 1)
3769 }
3770 };
3771 while k >= 0 {
3772 let ks = (k as u64).to_string();
3773 if has_array_elem(it, &t, &ks)? {
3774 let v = get_array_elem(it, &t, &ks)?;
3775 if v.strict_eq(&target) {
3776 return Ok(Value::Number(k as f64));
3777 }
3778 }
3779 k -= 1;
3780 }
3781 Ok(Value::Number(-1.0))
3782}
3783
3784pub(crate) fn arr_copy_within(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3785 if matches!(t, Value::Undefined | Value::Null) {
3786 return Err(it.type_error("Array.prototype method called on null or undefined"));
3787 }
3788 let obj = if matches!(t, Value::Object(_)) {
3789 t.clone()
3790 } else {
3791 super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3792 };
3793 let len_val = it.get_property(&obj, "length")?;
3794 let len = to_length_u64_checked(it, &len_val)?;
3795 let to_n = it.num_of(&arg(a, 0))?;
3796 let to = norm_index_u64(to_n, len);
3797 let from_n = if matches!(arg(a, 1), Value::Undefined) {
3798 0.0
3799 } else {
3800 it.num_of(&arg(a, 1))?
3801 };
3802 let from = norm_index_u64(from_n, len);
3803 let end_n = if matches!(arg(a, 2), Value::Undefined) {
3804 len as f64
3805 } else {
3806 it.num_of(&arg(a, 2))?
3807 };
3808 let fin = norm_index_u64(end_n, len);
3809 let mut count = if fin > from {
3810 (fin - from).min(len - to)
3811 } else {
3812 0
3813 };
3814 if count == 0 {
3815 return Ok(obj);
3816 }
3817 let is_fast_bytes = matches!(&obj, Value::Object(o) if matches!(&o.borrow().kind, ObjKind::Bytes(_)));
3818 if is_fast_bytes {
3819 if let Value::Object(o) = &obj {
3820 let mut b = o.borrow_mut();
3821 if let ObjKind::Bytes(st) = &mut b.kind {
3822 let c = count as usize;
3823 let f = from as usize;
3824 let dst = to as usize;
3825 let cur_len = st.effective_len();
3826 let vals: Vec<Option<Value>> = (f..f + c).map(|i| st.get_value(i)).collect();
3827 for (i, v) in vals.into_iter().enumerate() {
3828 if dst + i < cur_len {
3829 if let Some(val) = v {
3830 st.set_value(dst + i, &val);
3831 }
3832 }
3833 }
3834 }
3835 }
3836 return Ok(obj);
3837 }
3838 let forward = !(from < to && to < from + count);
3840 let mut from_idx = if forward { from } else { from + count - 1 };
3841 let mut to_idx = if forward { to } else { to + count - 1 };
3842 while count > 0 {
3843 if it.tick() {
3844 return Err(Value::Undefined);
3845 }
3846 let from_key = from_idx.to_string();
3847 let to_key = to_idx.to_string();
3848 if has_array_elem(it, &obj, &from_key)? {
3849 let from_val = get_array_elem(it, &obj, &from_key)?;
3850 put_prop_strict(it, &obj, &to_key, from_val)?;
3851 } else {
3852 del_prop_strict(it, &obj, &to_key)?;
3853 }
3854 if forward {
3855 from_idx += 1;
3856 to_idx += 1;
3857 } else if count > 1 {
3858 from_idx -= 1;
3859 to_idx -= 1;
3860 }
3861 count -= 1;
3862 }
3863 Ok(obj)
3864}
3865
3866pub(crate) fn is_typed_array(t: &Value) -> bool {
3873 if let Value::Object(o) = t {
3874 o.borrow().props.contains_key("_ta_kind")
3875 } else {
3876 false
3877 }
3878}
3879
3880pub(crate) fn array_species_create(
3885 it: &mut Interp,
3886 original: &Value,
3887 length: usize,
3888) -> Result<Value, Value> {
3889 let init_cap = length.min(4096);
3890 let is_array = super::object_array::is_array_value(it, original)?;
3891 if !is_array {
3892 return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3893 }
3894
3895 let ctor = it.get_property(original, "constructor")?;
3896 if matches!(ctor, Value::Undefined) {
3897 return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3898 }
3899 if !matches!(ctor, Value::Object(_)) {
3900 return Err(it.type_error("Array constructor is not an object"));
3901 }
3902
3903 let species_val = it.get_property(&ctor, "Symbol(Symbol.species)")?;
3905 if matches!(species_val, Value::Null | Value::Undefined) {
3906 return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3907 }
3908
3909 if let Value::Object(ref so) = species_val {
3911 if let Some(Value::Object(ref ao)) = it.global.borrow().vars.get("Array") {
3912 if core::ptr::eq(so.as_ref(), ao.as_ref()) {
3913 return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3914 }
3915 }
3916 }
3917 if super::super::interp::calls::is_constructor(&species_val) {
3918 return it.construct_value(&species_val, &[Value::Number(length as f64)]);
3919 }
3920
3921 Err(it.type_error("Symbol.species is not a constructor"))
3922}
3923
3924pub(crate) fn populate_array_species(
3925 it: &mut Interp,
3926 target: &Value,
3927 items: alloc::vec::Vec<Value>,
3928) -> Result<Value, Value> {
3929 if let Value::Object(o) = target {
3930 let can_fast = {
3931 let b = o.borrow();
3932 matches!(b.kind, ObjKind::Array(_))
3933 && !b.has_rare_props()
3934 && !b.is_frozen()
3935 && !b.is_sealed()
3936 && !b.is_non_extensible()
3937 };
3938 if can_fast {
3939 let len = items.len();
3940 o.borrow_mut().kind = ObjKind::Array(items);
3941 o.borrow_mut().props.insert("length".into(), Value::Number(len as f64));
3942 return Ok(target.clone());
3943 }
3944 }
3945 let len = items.len();
3946 for (i, v) in items.into_iter().enumerate() {
3947 super::object_array::create_data_property_or_throw(it, target, &i.to_string(), v)?;
3948 }
3949 let _ = len;
3950 Ok(target.clone())
3951}
3952
3953pub(crate) fn same_kind_as(it: &mut Interp, t: &Value, items: alloc::vec::Vec<Value>) -> Value {
3954 let ta_kind_tag = if let Value::Object(o) = t {
3955 o.borrow().props.get("_ta_kind").map(|v| v.to_js_string())
3956 } else {
3957 None
3958 };
3959 match ta_kind_tag {
3960 Some(tag) => {
3961 let kind = TaKind::from_name(&tag);
3965 let values: alloc::vec::Vec<f64> = items.iter().map(|v| kind.convert(v)).collect();
3966 make_typed_array(it, values, kind)
3967 }
3968 None => Value::Object(Obj::array(items)),
3969 }
3970}
3971pub(crate) fn arr_to_sorted(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3972 if matches!(t, Value::Undefined | Value::Null) {
3973 return Err(it.type_error("Array.prototype method called on null or undefined"));
3974 }
3975 let items = generic_array_items(it, &t);
3976 let cmp = arg(a, 0);
3977 let items = sort_excluding_undefined(it, items, &cmp)?;
3978 Ok(same_kind_as(it, &t, items))
3979}
3980
3981pub(crate) fn arr_to_reversed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
3982 if matches!(t, Value::Undefined | Value::Null) {
3983 return Err(it.type_error("Array.prototype method called on null or undefined"));
3984 }
3985 let mut items = generic_array_items(it, &t);
3986 items.reverse();
3987 Ok(same_kind_as(it, &t, items))
3988}
3989
3990pub(crate) fn arr_to_spliced(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3991 if matches!(t, Value::Undefined | Value::Null) {
3992 return Err(it.type_error("Array.prototype method called on null or undefined"));
3993 }
3994 let len_val = it.get_property(&t, "length")?;
3995 let len = to_length_u64_checked(it, &len_val)?;
3996 let actual_start = norm_index_u64(it.num_of(&arg(a, 0))?, len);
3997 let insert_count = a.len().saturating_sub(2) as u64;
3998 let actual_delete_count = if a.is_empty() {
3999 0
4001 } else if a.len() < 2 {
4002 len - actual_start
4003 } else {
4004 let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
4005 if dc <= 0.0 {
4006 0
4007 } else if dc == f64::INFINITY || dc >= ((len - actual_start) as f64) {
4008 len - actual_start
4009 } else {
4010 dc as u64
4011 }
4012 };
4013 let new_len = len - actual_delete_count + insert_count;
4014 if new_len > MAX_SAFE_INT_U64 {
4015 return Err(it.type_error("Invalid array length"));
4016 }
4017 if new_len > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
4018 return Err(it.range_error("Invalid array length"));
4019 }
4020 let mut out = try_vec_with_capacity::<Value>(it, new_len as usize)?;
4021 if is_dense_plain_array(&t) {
4022 let items = this_items(&t);
4023 for k in 0..actual_start as usize {
4024 out.push(items.get(k).cloned().unwrap_or(Value::Undefined));
4025 }
4026 for v in a.iter().skip(2) {
4027 out.push(v.clone());
4028 }
4029 out.extend(
4030 items
4031 .iter()
4032 .skip((actual_start + actual_delete_count) as usize)
4033 .cloned(),
4034 );
4035 } else {
4036 for k in 0..actual_start {
4037 out.push(get_array_elem(it, &t, &k.to_string())?);
4038 }
4039 for v in a.iter().skip(2) {
4040 out.push(v.clone());
4041 }
4042 for k in (actual_start + actual_delete_count)..len {
4043 out.push(get_array_elem(it, &t, &k.to_string())?);
4044 }
4045 }
4046 Ok(same_kind_as(it, &t, out))
4047}
4048
4049fn arr_find_last_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4050 find_core(it, t, a, true, false)
4051}
4052
4053fn arr_find_last_index_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4054 find_core(it, t, a, true, true)
4055}
4056
4057fn arr_reduce_right_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4059 let t = to_object_required(it, &t, "reduceRight")?;
4060 let len_val = it.get_property(&t, "length")?;
4061 let len = to_length_u64(&Value::Number(if matches!(len_val, Value::Object(_)) { it.num_of(&len_val)? } else { len_val.to_number() }));
4062 let f = arg(a, 0);
4063 if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
4064 return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(&f))));
4065 }
4066 let mut k: i128 = (len as i128) - 1;
4067 let mut acc = if a.len() > 1 {
4068 arg(a, 1)
4069 } else {
4070 let mut init: Option<Value> = None;
4071 while k >= 0 {
4072 let ks = (k as u64).to_string();
4073 if has_array_elem(it, &t, &ks)? {
4074 init = Some(get_array_elem(it, &t, &ks)?);
4075 k -= 1;
4076 break;
4077 }
4078 k -= 1;
4079 }
4080 match init {
4081 Some(v) => v,
4082 None => return Err(it.type_error("Reduce of empty array with no initial value")),
4083 }
4084 };
4085 while k >= 0 {
4086 let ku = k as u64;
4087 let ks = ku.to_string();
4088 if has_array_elem(it, &t, &ks)? {
4089 let v = get_array_elem(it, &t, &ks)?;
4090 acc = it.call_value(&f, Value::Undefined, &[acc, v, Value::Number(ku as f64), t.clone()])?;
4091 }
4092 k -= 1;
4093 }
4094 Ok(acc)
4095}
4096
4097pub(crate) fn arr_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4100 if matches!(t, Value::Undefined | Value::Null) {
4101 return Err(it.type_error("Array.prototype method called on null or undefined"));
4102 }
4103 let mut items = generic_array_items(it, &t);
4104 let len = items.len() as i64;
4105 let idx_raw = it.num_of(&arg(a, 0))? as i64;
4106 let idx = if idx_raw < 0 { len + idx_raw } else { idx_raw };
4107 if idx < 0 || idx >= len {
4108 return Err(it.range_error("Invalid index"));
4109 }
4110 items[idx as usize] = arg(a, 1);
4111 Ok(same_kind_as(it, &t, items))
4112}
4113
4114pub(crate) fn flatten_depth(items: Vec<Value>, depth: f64, out: &mut Vec<Value>, seen: &mut Vec<ObjRef>) {
4123 for v in items {
4124 match v {
4125 Value::Object(o) if depth > 0.0 && matches!(o.borrow().kind, ObjKind::Array(_)) => {
4126 if seen.iter().any(|s| Rc::ptr_eq(s, &o)) {
4127 out.push(Value::Object(o));
4128 continue;
4129 }
4130 seen.push(o.clone());
4131 let inner = {
4133 let b = o.borrow();
4134 match &b.kind {
4135 ObjKind::Array(inner) if b.holes().is_some() => inner
4136 .iter()
4137 .enumerate()
4138 .filter(|(i, _)| !b.is_hole(*i))
4139 .map(|(_, v)| v.clone())
4140 .collect(),
4141 ObjKind::Array(inner) => inner.clone(),
4142 _ => Vec::new(),
4143 }
4144 };
4145 flatten_depth(inner, depth - 1.0, out, seen);
4146 seen.pop();
4147 }
4148 other => out.push(other),
4149 }
4150 }
4151}
4152pub(crate) fn arr_flat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4156 if matches!(t, Value::Undefined | Value::Null) {
4157 return Err(it.type_error("Array.prototype method called on null or undefined"));
4158 }
4159 let items = without_holes(&t, generic_array_items(it, &t));
4160 let depth = if matches!(arg(a, 0), Value::Undefined) {
4161 1.0
4162 } else {
4163 it.num_of(&arg(a, 0))?
4164 };
4165 let mut out = Vec::new();
4166 flatten_depth(items, depth, &mut out, &mut Vec::new());
4167 Ok(Value::Object(Obj::array(out)))
4168}
4169pub(crate) fn has_own_property(o: &super::super::value::ObjRef, key: &str) -> bool {
4175 let o = unwrap_proxy_target(o);
4176 if key == "prototype" {
4177 let _ = Obj::fn_prototype(&o);
4178 }
4179 let b = o.borrow();
4180 if let ObjKind::Array(items) = &b.kind {
4181 if key == "length" {
4182 return true;
4183 }
4184 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4185 return idx < items.len() && !b.is_hole(idx);
4186 }
4187 }
4188 if let ObjKind::Bytes(st) = &b.kind {
4189 if key == "length" {
4190 return true;
4191 }
4192 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4193 return idx < st.len;
4194 }
4195 }
4196 if let ObjKind::Plain = &b.kind {
4197 if let Some(Value::Str(s)) = b.primitive() {
4198 if !(s.starts_with("Symbol(") && s.ends_with(')')) {
4199 if key == "length" {
4200 return true;
4201 }
4202 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4203 if idx < Units::of(s).len() {
4204 return true;
4205 }
4206 }
4207 }
4208 }
4209 }
4210 b.props.contains_key(key) || b.has_accessor(key) || b.has_virtual_fn_prop(key)
4211}
4212pub(crate) fn obj_has_own(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4213 let pk = it.prim_key(arg(a, 0))?;
4214 let key = super::super::interp::to_property_key(&pk).into_owned();
4215 if matches!(t, Value::Undefined | Value::Null) {
4216 return Err(it.type_error("Cannot convert undefined or null to object"));
4217 }
4218 if let Value::Object(o) = &t {
4219 let host_ref = o.borrow().kind.host_ref();
4221 if let Some(h) = host_ref {
4222 match (it.host.own)(it, h, &key) {
4223 HostOwn::Generic => {}
4224 HostOwn::Absent => return Ok(Value::Bool(false)),
4225 HostOwn::Accessor(..) | HostOwn::Data(_) => return Ok(Value::Bool(true)),
4226 }
4227 }
4228 if key == "prototype" {
4229 let _ = Obj::fn_prototype(o);
4230 }
4231 return Ok(Value::Bool(has_own_property(o, &key)));
4232 }
4233 if let Value::Str(s) = &t {
4235 if !is_symbol_like_key(s) {
4236 let n = Units::of(s).len();
4237 return Ok(Value::Bool(
4238 key == "length" || crate::os_lib::ecma::value::parse_index(&key).is_some_and(|i| i < n),
4239 ));
4240 }
4241 }
4242 Ok(Value::Bool(false))
4243}
4244pub(crate) fn obj_proto_get(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4250 if matches!(t, Value::Undefined | Value::Null) {
4251 return Err(it.type_error("Cannot convert undefined or null to object"));
4252 }
4253 let obj = match &t {
4254 Value::Object(_) => t,
4255 _ => super::object_array::object_ctor(it, Value::Undefined, &[t])?,
4256 };
4257 super::extra_static::object_get_prototype_of(it, Value::Undefined, &[obj])
4258}
4259
4260pub(crate) fn obj_proto_set(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4261 if matches!(t, Value::Undefined | Value::Null) {
4262 return Err(it.type_error("Cannot convert undefined or null to object"));
4263 }
4264 let proto = arg(a, 0);
4265 if !matches!(proto, Value::Object(_) | Value::Null) {
4266 return Ok(Value::Undefined);
4267 }
4268 if !matches!(t, Value::Object(_)) {
4269 return Ok(Value::Undefined);
4270 }
4271 super::extra_static::object_set_prototype_of(it, Value::Undefined, &[t, proto])?;
4272 Ok(Value::Undefined)
4273}
4274
4275pub(crate) fn obj_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4276 let builtin_tag = match &t {
4280 Value::Undefined => "Undefined",
4281 Value::Null => "Null",
4282 Value::Object(o) => {
4283 let target = unwrap_proxy_target(o);
4284 let b = target.borrow();
4285 if b.is_callable() {
4286 "Function"
4287 } else {
4288 match &b.kind {
4289 ObjKind::Array(_) if b.props.contains_key("callee") || b.has_accessor("callee") => "Arguments",
4290 ObjKind::Array(_) => "Array",
4291 ObjKind::DateObj(_) => "Date",
4292 ObjKind::RegExpObj(_) => "RegExp",
4293 ObjKind::Bytes(_) => {
4294 if let Some(k) = b.props.get("_ta_kind") {
4295 return Ok(Value::str(format!("[object {}]", k.to_js_string())));
4296 }
4297 "Object"
4298 }
4299 ObjKind::Plain if b.primitive().is_some() => match b.primitive() {
4300 Some(Value::Number(_)) => "Number",
4301 Some(Value::Str(s)) if super::is_symbol_like_key(s) => "Object",
4302 Some(Value::Str(_)) => "String",
4303 Some(Value::BigInt(_)) => "BigInt",
4304 _ => "Boolean",
4305 },
4306 ObjKind::Plain if b.is_error_obj() => "Error",
4307 _ => "Object",
4308 }
4309 }
4310 }
4311 Value::Str(s) if super::is_symbol_like_key(s) => "Object",
4312 Value::Str(_) => "String",
4313 Value::Number(_) => "Number",
4314 Value::Bool(_) => "Boolean",
4315 Value::BigInt(_) => "BigInt",
4316 };
4317 if !matches!(&t, Value::Undefined | Value::Null) {
4318 let tag_val = it.get_property(&t, "Symbol(Symbol.toStringTag)")?;
4319 if let Value::Str(s) = tag_val {
4320 if !super::is_symbol_like_key(&s) {
4321 return Ok(Value::str(format!("[object {}]", s)));
4322 }
4323 }
4324 }
4325 Ok(Value::str(format!("[object {}]", builtin_tag)))
4326}
4327pub(crate) fn obj_is_prototype_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4330 let Value::Object(candidate) = arg(a, 0) else {
4331 return Ok(Value::Bool(false));
4332 };
4333 if matches!(t, Value::Undefined | Value::Null) {
4334 return Err(it.type_error("Cannot convert undefined or null to object"));
4335 }
4336 let target_val = super::object_array::object_ctor(it, Value::Undefined, &[t])?;
4337 let Value::Object(target) = target_val else {
4338 return Ok(Value::Bool(false));
4339 };
4340 let mut cur = super::extra_static::implicit_proto(it, &candidate);
4341 let mut guard = 0;
4342 while let Some(p) = cur {
4343 if Rc::ptr_eq(&p, &target) {
4344 return Ok(Value::Bool(true));
4345 }
4346 cur = super::extra_static::implicit_proto(it, &p);
4347 guard += 1;
4348 if guard > 1000 {
4349 break;
4350 }
4351 }
4352 Ok(Value::Bool(false))
4353}
4354pub(crate) fn obj_property_is_enumerable(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4358 let own = obj_has_own(it, t.clone(), a)?;
4359 if !own.truthy() {
4360 return Ok(own);
4361 }
4362 let key = it.to_string_value(arg(a, 0))?;
4365 Ok(Value::Bool(match &t {
4366 Value::Str(_) => key != "length",
4367 Value::Object(o) => {
4368 let b = o.borrow();
4369 if matches!(b.kind, ObjKind::Array(_) | ObjKind::Bytes(_)) && key == "length" {
4370 false
4371 } else {
4372 b.is_enumerable(&key)
4373 }
4374 }
4375 _ => true,
4376 }))
4377}
4378
4379pub fn function_method_fn(key: &str) -> Option<(&'static str, NativeFn)> {
4383 match key {
4384 "call" => Some(("call", fn_call)),
4385 "apply" => Some(("apply", fn_apply)),
4386 "bind" => Some(("bind", fn_bind)),
4387 "toString" => Some(("toString", fn_to_string)),
4389 _ => None,
4390 }
4391}
4392
4393pub fn function_method(key: &str) -> Value {
4394 match function_method_fn(key) {
4395 Some((n, f)) => nv(n, f),
4396 None => Value::Undefined,
4397 }
4398}
4399pub(crate) fn fn_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4402 match &t {
4403 Value::Object(o) if o.borrow().is_callable() => {
4404 let b = o.borrow();
4405 match &b.kind {
4406 ObjKind::Native { name, .. } => Ok(Value::str(alloc::format!(
4407 "function {}() {{ [native code] }}",
4408 crate::os_lib::ecma::fn_meta::native_name_string(name)
4409 ))),
4410 ObjKind::Bound(_) | ObjKind::Resolver { .. } | ObjKind::Proxy(_) => {
4411 Ok(Value::str("function () { [native code] }"))
4412 }
4413 _ => {
4414 drop(b);
4415 Ok(Value::str(t.to_js_string()))
4416 }
4417 }
4418 }
4419 Value::Object(o) if o.borrow().kind.host_ref().is_some() => {
4422 Ok(Value::str("function () { [native code] }"))
4423 }
4424 _ => Err(it.type_error("Function.prototype.toString requires that 'this' be a Function")),
4425 }
4426}
4427pub(crate) fn fn_call(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4428 let this_arg = arg(a, 0);
4429 let rest: Vec<Value> = a.get(1..).map(|s| s.to_vec()).unwrap_or_default();
4430 it.call_value(&t, this_arg, &rest)
4431}
4432pub(crate) fn fn_apply(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4437 let this_arg = arg(a, 0);
4438 let args_vec = match arg(a, 1) {
4439 Value::Undefined | Value::Null => Vec::new(),
4440 v => array_like_items(it, &v),
4441 };
4442 it.call_value(&t, this_arg, &args_vec)
4443}
4444pub(crate) fn fn_bind(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4445 let Value::Object(target_obj) = &t else {
4446 return Err(it.type_error("Function.prototype.bind called on non-callable"));
4447 };
4448 if !target_obj.borrow().is_callable() {
4449 return Err(it.type_error("Function.prototype.bind called on non-callable"));
4450 }
4451 let bound_this = arg(a, 0);
4452 let bound_args: Vec<Value> = a.get(1..).map(|s| s.to_vec()).unwrap_or_default();
4453 let needs_dynamic = {
4454 let b = target_obj.borrow();
4455 matches!(b.kind, ObjKind::Proxy(_))
4456 || b.props.contains_key("length")
4457 || b.props.contains_key("name")
4458 || b.has_accessor("length")
4459 || b.has_accessor("name")
4460 || !b.has_virtual_fn_prop("length")
4461 || !b.has_virtual_fn_prop("name")
4462 };
4463 let bound_obj = Obj::bound(t.clone(), bound_this, bound_args.clone());
4464 if needs_dynamic {
4465 let has_len = has_own_property(target_obj, "length");
4468 let len_num = if has_len {
4469 match it.get_property(&t, "length")? {
4470 Value::Number(n) => {
4471 if n.is_nan() || n <= 0.0 || n == f64::NEG_INFINITY {
4472 0.0
4473 } else if n == f64::INFINITY {
4474 f64::INFINITY
4475 } else {
4476 (libm::trunc(n) - (bound_args.len() as f64)).max(0.0)
4477 }
4478 }
4479 _ => 0.0,
4480 }
4481 } else {
4482 0.0
4483 };
4484 let target_name = match it.get_property(&t, "name")? {
4485 Value::Str(s) => (*s).clone(),
4486 _ => String::new(),
4487 };
4488 let bound_name = format!("bound {}", target_name);
4489 let default_attr = super::super::value::PropertyAttributes {
4490 writable: false,
4491 enumerable: false,
4492 configurable: true,
4493 };
4494 let mut bb = bound_obj.borrow_mut();
4495 let same_len = matches!(super::virtual_fn_prop_value(&bb, "length"), Some(Value::Number(n)) if n == len_num);
4496 if !same_len {
4497 bb.props.insert("length".into(), Value::Number(len_num));
4498 bb.delete_virtual_fn_prop("length");
4499 bb.insert_attr("length", default_attr);
4500 }
4501 if super::virtual_fn_prop_value(&bb, "name").as_ref().map(Value::to_js_string).as_deref() != Some(bound_name.as_str()) {
4502 bb.props.insert("name".into(), Value::str(bound_name));
4503 bb.delete_virtual_fn_prop("name");
4504 bb.insert_attr("name", default_attr);
4505 }
4506 }
4507 Ok(Value::Object(bound_obj))
4508}
4509
4510pub(crate) fn norm_index(v: f64, len: i64, default: i64) -> i64 {
4513 if v.is_nan() {
4514 return default;
4515 }
4516 let i = libm::trunc(v) as i64;
4517 if i < 0 {
4518 (len + i).max(0)
4519 } else {
4520 i.min(len)
4521 }
4522}
4523pub(crate) fn clamp_idx(v: f64, len: usize) -> usize {
4524 if v.is_nan() || v < 0.0 {
4525 0
4526 } else {
4527 (v as usize).min(len)
4528 }
4529}
4530pub(crate) fn pad_str(s: &str, target: usize, pad: &str, start: bool) -> String {
4531 let cur = unit_len(s);
4532 if cur >= target || pad.is_empty() {
4533 return String::from(s);
4534 }
4535 let mut padding = String::new();
4536 let pad_chars: Vec<char> = pad.chars().collect();
4537 let mut i = 0;
4538 while padding.chars().count() < target - cur {
4539 padding.push(pad_chars[i % pad_chars.len()]);
4540 i += 1;
4541 }
4542 if start {
4543 format!("{}{}", padding, s)
4544 } else {
4545 format!("{}{}", s, padding)
4546 }
4547}
4548pub(crate) fn format_fixed(n: f64, digits: usize) -> String {
4549 let neg = n < 0.0;
4550 let n = libm::fabs(n);
4551 let int_part = libm::trunc(n) as i64;
4552 let scale = libm::pow(10.0, digits as f64);
4553 let frac = libm::trunc((n - libm::trunc(n)) * scale + 0.5) as i64;
4554 let frac_str = format!("{:0width$}", frac, width = digits);
4555 format!("{}{}.{}", if neg { "-" } else { "" }, int_part, frac_str)
4556}
4557