1use super::*;
5
6impl Interp {
7 pub(crate) fn string_get_prop(&self, sv: &Value, key: &str) -> Value {
8 if key == "length" {
9 return Value::Number(super::super::builtins::cached_units(self, sv).len() as f64);
10 }
11 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
12 let u = super::super::builtins::cached_units(self, sv);
13 return if idx < u.len() { self.char_unit_val(u.at(idx)) } else { Value::Undefined };
14 }
15 super::super::builtins::string_builtin_fn(key)
16 .map(|(name, f)| self.builtin_fn_val(name, f))
17 .unwrap_or(Value::Undefined)
18 }
19
20 pub(crate) fn number_get_prop(&self, key: &str) -> Value {
21 super::super::builtins::number_builtin_fn(key)
22 .map(|(name, f)| self.builtin_fn_val(name, f))
23 .unwrap_or(Value::Undefined)
24 }
25
26 pub(crate) fn boolean_get_prop(&self, key: &str) -> Value {
27 super::super::builtins::boolean_builtin_fn(key)
28 .map(|(name, f)| self.builtin_fn_val(name, f))
29 .unwrap_or(Value::Undefined)
30 }
31
32 pub(crate) fn bigint_get_prop(&self, key: &str) -> Value {
33 super::super::builtins::bigint_builtin_fn(key)
34 .map(|(name, f)| self.builtin_fn_val(name, f))
35 .unwrap_or(Value::Undefined)
36 }
37
38 pub(crate) fn object_get_prop(&self, o: &ObjRef, key: &str) -> Value {
39 let is_array = matches!(o.borrow().kind, ObjKind::Array(_));
40 if is_array {
41 if let Some((name, f)) = super::super::builtins::array_builtin_fn(key) {
42 return self.builtin_fn_val(name, f);
43 }
44 }
45 if let Some((name, f)) = super::super::builtins::object_builtin_fn(key) {
46 return self.builtin_fn_val(name, f);
47 }
48 Value::Undefined
49 }
50
51 pub(crate) fn has_property_chain(&self, o: &ObjRef, key: &str) -> bool {
57 let mut cur = o.clone();
58 let mut guard = 0u32;
59 loop {
60 let b = cur.borrow();
61 if let ObjKind::Array(items) = &b.kind {
62 if key == "length" {
63 return true;
64 }
65 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
66 if idx < items.len() && !b.is_hole(idx) {
67 return true;
68 }
69 }
70 }
71 if matches!(&b.kind, ObjKind::Bytes(_))
72 && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
73 {
74 return crate::os_lib::ecma::value::ta_valid_index(&b, key).is_some();
75 }
76 if b.props.contains_key(key) || b.has_accessor(key) {
80 return true;
81 }
82 if let Some(h) = b.kind.host_ref() {
83 if !matches!(
84 (self.host.own)(self, h, key),
85 crate::os_lib::ecma::host::HostOwn::Generic | crate::os_lib::ecma::host::HostOwn::Absent
86 ) {
87 return true;
88 }
89 }
90 guard += 1;
91 if guard > 1000 {
92 return false;
93 }
94 let next = b.proto.clone();
95 let null_proto = b.is_null_proto();
96 let host_proto = if next.is_none() && !null_proto {
97 self.host_proto_of(&b.kind).flatten()
98 } else {
99 None
100 };
101 drop(b);
102 match next.or(host_proto) {
103 Some(p) => cur = p,
104 None => {
109 if null_proto {
110 return false;
111 }
112 if matches!(key, "constructor" | "__proto__") {
113 return true;
114 }
115 if o.borrow().is_callable() && matches!(key, "call" | "apply" | "bind" | "name" | "length") {
116 return true;
117 }
118 return !matches!(super::super::builtins::object_get(o, key), Value::Undefined);
119 }
120 }
121 }
122 }
123
124 pub(crate) fn is_global_obj(&self, o: &crate::os_lib::ecma::value::ObjRef) -> bool {
126 matches!(self.global.borrow().vars.get("globalThis"), Some(Value::Object(w)) if alloc::rc::Rc::ptr_eq(w, o))
127 }
128
129 pub(crate) fn is_window_obj(&self, o: &crate::os_lib::ecma::value::ObjRef) -> bool {
131 self.is_global_obj(o)
132 }
133
134 pub fn get_property_of_expr(
138 &mut self,
139 recv: &Value,
140 key: &str,
141 obj_expr: &crate::os_lib::ecma::ast::Expression,
142 ) -> EvalResult {
143 let r = self.get_property(recv, key);
144 if let (Err(Value::Object(o)), Value::Undefined | Value::Null) = (&r, recv) {
145 let desc = describe_expr(obj_expr);
146 let stack = o.borrow().error_stack().unwrap_or("").to_string();
147 let mut lines = stack.splitn(2, '\n');
148 let first = lines.next().unwrap_or("");
149 let rest = lines.next();
150 let mut ns = alloc::format!("{first}\n (undefined だった式: {desc})");
151 if let Some(rest) = rest {
152 ns.push('\n');
153 ns.push_str(rest);
154 }
155 o.borrow_mut().set_error_stack(ns);
156 }
157 r
158 }
159
160 #[inline]
168 pub(crate) fn get_index_fast(&self, obj: &Value, key: &Value) -> Option<Value> {
169 let Value::Number(n) = key else { return None };
170 let n = *n;
171 if !(0.0..4_294_967_295.0).contains(&n) || (n as u32) as f64 != n {
172 return None;
173 }
174 let i = n as usize;
175 match obj {
176 Value::Object(o) => {
177 let b = o.borrow();
178 match &b.kind {
179 ObjKind::Array(_) if b.has_any_accessor() => None,
180 ObjKind::Array(items) => Some(items.get(i).cloned().unwrap_or(Value::Undefined)),
181 ObjKind::Bytes(st) => {
182 if crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) {
183 Some(Value::Undefined)
184 } else if i < st.effective_len() {
185 Some(st.get_value(i).unwrap_or(Value::Undefined))
186 } else {
187 Some(Value::Undefined)
188 }
189 }
190 _ => None,
191 }
192 }
193 Value::Str(_) => {
194 let units = super::super::builtins::cached_units(self, obj);
195 if i < units.len() {
196 Some(self.char_unit_val(units.at(i)))
197 } else {
198 Some(Value::Undefined)
199 }
200 }
201 _ => None,
202 }
203 }
204
205 #[inline]
211 pub(crate) fn set_index_fast(&mut self, obj: &Value, key: &Value, val: Value) -> Option<Value> {
212 let (Value::Object(o), Value::Number(n)) = (obj, key) else { return Some(val) };
213 let n = *n;
214 if !(0.0..4_294_967_295.0).contains(&n) || (n as u32) as f64 != n {
215 return Some(val);
216 }
217 let i = n as usize;
218 let mut b = o.borrow_mut();
219 if b.is_frozen() || b.is_sealed() || b.is_non_extensible() || b.has_rare_props() {
220 return Some(val);
221 }
222 if let ObjKind::Bytes(st) = &b.kind {
223 if super::super::value::ByteStore::is_bigint_kind(st.raw_kind())
224 || !matches!(val, Value::Number(_))
225 || crate::os_lib::ecma::value::ta_is_immutable(&b)
226 {
227 return Some(val);
228 }
229 if !crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) && i < st.effective_len() {
230 st.set_value(i, &val);
231 }
232 return None;
233 }
234 let ta_kind = if !b.props.is_empty() {
235 if let Some(t) = b.props.get("_ta_kind") {
236 if b.props.contains_key("_view_root") {
237 return Some(val);
238 }
239 match t {
240 Value::Str(s) => Some(super::super::builtins::TaKind::from_name(s.as_str())),
241 _ => None,
242 }
243 } else {
244 None
245 }
246 } else {
247 None
248 };
249 if matches!(val, Value::Undefined) && b.rare.is_some() {
251 b.clear_hole(i);
252 }
253 if let ObjKind::Array(items) = &mut b.kind {
254 if i < items.len() {
255 items[i] = match ta_kind {
256 Some(ta) => Value::Number(ta.convert(&val)),
257 None => val,
258 };
259 return None;
260 } else if i == items.len() && i < 1_000_000 {
261 let val_coerced = match ta_kind {
262 Some(ta) => Value::Number(ta.convert(&val)),
263 None => val,
264 };
265 items.push(val_coerced);
266 return None;
267 }
268 }
269 Some(val)
270 }
271
272 pub fn get_property(&mut self, recv: &Value, key: &str) -> EvalResult {
273 match recv {
274 Value::Undefined | Value::Null => Err(self.type_error(format!(
275 "Cannot read properties of {} (reading '{}')",
276 recv.to_js_string(),
277 key
278 ))),
279 Value::Str(_) | Value::Number(_) | Value::BigInt(_) | Value::Bool(_) => {
280 let is_sym = matches!(recv, Value::Str(s) if super::super::builtins::is_symbol_like_key(s));
281 let ctor = match recv {
282 Value::Str(_) if is_sym => "Symbol",
283 Value::Str(_) => "String",
284 Value::Number(_) => "Number",
285 Value::BigInt(_) => "BigInt",
286 _ => "Boolean",
287 };
288 if !is_sym
291 && matches!(recv, Value::Str(_))
292 && (key == "length" || crate::os_lib::ecma::value::parse_index(key).is_some())
293 {
294 let v = self.string_get_prop(recv, key);
295 if !matches!(v, Value::Undefined) || key == "length" {
296 return Ok(v);
297 }
298 }
299 if let Some(p) = super::super::builtins::global_ctor_proto(self, ctor) {
300 if let Some(r) = self.proto_chain_lookup(recv, &p, key, Some(p.clone())) {
301 return r;
302 }
303 }
304 let v = match recv {
305 Value::Str(_) if is_sym => Value::Undefined,
306 Value::Str(_) => self.string_get_prop(recv, key),
307 Value::Number(_) => self.number_get_prop(key),
308 Value::BigInt(_) => self.bigint_get_prop(key),
309 _ => self.boolean_get_prop(key),
310 };
311 if !matches!(v, Value::Undefined) {
312 return Ok(v);
313 }
314 Ok(Value::Undefined)
319 }
320 Value::Object(o) => {
321 let mut plain_proto_start = None;
325 {
326 let b = o.borrow();
327 match &b.kind {
328 ObjKind::Plain if key != "__proto__" => {
329 if let Some(a) = b.get_accessor(key) {
330 let getter = a.get.clone();
331 drop(b);
332 return if let Some(g) = getter {
333 self.call_value(&g, recv.clone(), &[])
334 } else {
335 Ok(Value::Undefined)
336 };
337 }
338 if let Some(v) = b.props.get(key) {
339 return Ok(v.clone());
340 }
341 if let Some(p) = b.primitive() {
343 let p = p.clone();
344 drop(b);
345 return self.get_property(&p, key);
346 }
347 if key != "selectedIndex" && key != "size" {
348 plain_proto_start = Some(b.proto.clone());
349 }
350 }
351 ObjKind::Array(items) => {
352 if key == "length" {
353 return Ok(Value::Number(items.len() as f64));
354 }
355 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
356 if let Some(a) = b.get_accessor(key) {
357 let getter = a.get.clone();
358 drop(b);
359 return match getter {
360 Some(g) => self.call_value(&g, recv.clone(), &[]),
361 None => Ok(Value::Undefined),
362 };
363 }
364 return Ok(items.get(idx).cloned().unwrap_or(Value::Undefined));
365 }
366 }
367 ObjKind::Bytes(st)
368 if crate::os_lib::ecma::value::is_canonical_numeric_key(key) =>
369 {
370 if let Some(idx) = crate::os_lib::ecma::value::ta_valid_index(&b, key) {
371 return Ok(st.get_value(idx).unwrap_or(Value::Undefined));
372 }
373 return Ok(Value::Undefined);
374 }
375 ObjKind::HostRef(h) if key != "__proto__" && key != "selectedIndex" => {
376 let h = *h;
377 drop(b);
378 if let Some(v) = self.host_get(o, h, key) {
379 return Ok(v);
380 }
381 }
382 _ => {}
383 }
384 }
385 if let Some(first_proto) = plain_proto_start {
386 if !self.is_window_obj(o) {
387 let first = match first_proto {
388 Some(p) => Some(p),
389 None => super::super::builtins::implicit_proto(self, o),
390 };
391 return self.get_property_proto_chain(recv, o, key, first);
392 }
393 }
394
395 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
397 return super::super::builtins::pm_get(self, o, key, recv);
398 }
399 if key == "prototype" && matches!(o.borrow().kind, ObjKind::Function(_)) {
408 if let Some(v) = Obj::fn_prototype(o) {
409 return Ok(v);
410 }
411 }
412 if key == "prototype"
413 && matches!(o.borrow().kind, ObjKind::Native { .. })
414 && !o.borrow().props.contains_key("prototype")
415 && !matches!(&o.borrow().kind, ObjKind::Native { name, .. } if &**name == "Proxy")
417 && super::calls::is_constructor(&Value::Object(o.clone()))
419 {
420 let proto = Obj::plain();
421 proto.borrow_mut().props.insert("constructor".into(), Value::Object(o.clone()));
422 o.borrow_mut().props.insert("prototype".into(), Value::Object(proto.clone()));
423 return Ok(Value::Object(proto));
424 }
425 if self.is_window_obj(o) && !o.borrow().props.contains_key(key) {
426 if !self.global_lexicals.borrow().contains(key) {
427 if let Some(v) = self.global.borrow().vars.get(key).cloned() {
428 return Ok(v);
429 }
430 }
431 if key.as_bytes().first().is_some_and(|c| c.is_ascii_uppercase()) && !o.borrow().has_accessor(key) {
434 super::exec::note_engine_error(&alloc::format!("missing window.{}", key), || ());
435 }
436 }
437 if key == "value" || key == "selectedIndex" {
439 if let Some(v) = (self.host.special_get)(self, o, key) {
440 return Ok(v);
441 }
442 }
443 let host_ref = o.borrow().kind.host_ref();
445 if let Some(h) = host_ref {
446 if let Some(v) = self.host_get(o, h, key) {
447 return Ok(v);
448 }
449 }
450 let is_iterator = matches!(&o.borrow().kind, ObjKind::Iter);
454 if is_iterator {
455 if o.borrow().props.contains_key(key) || o.borrow().has_accessor(key) {
458 } else {
460 let start = super::super::builtins::implicit_proto(self, o);
461 if let Some(res) = self.proto_chain_lookup(recv, o, key, start) {
462 return res;
463 }
464 if let Some(m) = match key {
465 "next" => Some(self.builtin_fn_val("next", super::super::builtins::iterator_next)),
466 "Symbol(Symbol.iterator)" => Some(self.builtin_fn_val(
467 "[Symbol.iterator]",
468 super::super::builtins::iterator_self,
469 )),
470 "map" => Some(self.builtin_fn_val("map", super::super::builtins::iterator_map)),
471 "filter" => Some(self.builtin_fn_val("filter", super::super::builtins::iterator_filter)),
472 "take" => Some(self.builtin_fn_val("take", super::super::builtins::iterator_take)),
473 "drop" => Some(self.builtin_fn_val("drop", super::super::builtins::iterator_drop)),
474 "toArray" => Some(self.builtin_fn_val("toArray", super::super::builtins::iterator_to_array)),
475 "forEach" => Some(self.builtin_fn_val("forEach", super::super::builtins::iterator_for_each)),
476 "reduce" => Some(self.builtin_fn_val("reduce", super::super::builtins::iterator_reduce)),
477 "some" => Some(self.builtin_fn_val("some", super::super::builtins::iterator_some)),
478 "every" => Some(self.builtin_fn_val("every", super::super::builtins::iterator_every)),
479 "find" => Some(self.builtin_fn_val("find", super::super::builtins::iterator_find)),
480 "flatMap" => Some(self.builtin_fn_val("flatMap", super::super::builtins::iterator_flat_map)),
481 "includes" => Some(self.builtin_fn_val("includes", super::super::builtins::iterator_includes)),
482 _ => None,
483 } {
484 return Ok(m);
485 }
486 return Ok(Value::Undefined);
487 }
488 }
489 if key != "size"
491 && matches!(
492 &o.borrow().kind,
493 ObjKind::MapObj(_) | ObjKind::SetObj(_) | ObjKind::PromiseObj(_) | ObjKind::DateObj(_)
494 )
495 {
496 if let Some(r) = self.proto_chain_lookup(recv, o, key, Some(o.clone())) {
497 return r;
498 }
499 }
500 let mapset = {
502 match &o.borrow().kind {
503 ObjKind::MapObj(e) => Some((true, e.len())),
504 ObjKind::SetObj(s) => Some((false, s.len())),
505 _ => None,
506 }
507 };
508 if let Some((is_map, len)) = mapset {
509 if key == "size" {
510 return Ok(Value::Number(len as f64));
511 }
512 if let Some((n, f)) = super::super::builtins::mapset_method_fn(is_map, key) {
513 return Ok(self.builtin_fn_val(n, f));
514 }
515 }
516 let is_promise = matches!(&o.borrow().kind, ObjKind::PromiseObj(_));
518 if is_promise {
519 if let Some((n, f)) = super::super::builtins::promise_method_fn(key) {
520 return Ok(self.builtin_fn_val(n, f));
521 }
522 }
523 let is_gen = matches!(&o.borrow().kind, ObjKind::Generator(_));
525 if is_gen {
526 if key == "Symbol(Symbol.iterator)" {
527 return Ok(self.builtin_fn_val("Generator[Symbol.iterator]", super::super::builtins::gen_self_iterator));
528 }
529 if key == "Symbol(Symbol.asyncIterator)" {
530 let is_async = if let ObjKind::Generator(g) = &o.borrow().kind {
531 g.borrow().func.is_async()
532 } else {
533 false
534 };
535 return Ok(if is_async {
536 self.builtin_fn_val("Generator[Symbol.iterator]", super::super::builtins::gen_self_iterator)
537 } else {
538 Value::Undefined
539 });
540 }
541 if let Some((n, f)) = super::super::builtins::generator_method_fn(key) {
542 return Ok(self.builtin_fn_val(n, f));
543 }
544 }
545 let is_date = matches!(&o.borrow().kind, ObjKind::DateObj(_));
547 if is_date {
548 if let Some((n, f)) = super::super::builtins::date_method_fn(key) {
549 return Ok(self.builtin_fn_val(n, f));
550 }
551 }
552 {
554 let b = o.borrow();
555 if let ObjKind::Array(items) = &b.kind {
556 if key == "length" {
557 return Ok(Value::Number(items.len() as f64));
558 }
559 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
560 return Ok(items.get(idx).cloned().unwrap_or(Value::Undefined));
561 }
562 }
563 if let ObjKind::Bytes(st) = &b.kind {
564 if crate::os_lib::ecma::value::is_canonical_numeric_key(key) {
565 if let Some(idx) = crate::os_lib::ecma::value::ta_valid_index(&b, key) {
566 return Ok(st.get_value(idx).unwrap_or(Value::Undefined));
567 }
568 return Ok(Value::Undefined);
569 }
570 }
571 }
572 if matches!(key, "call" | "apply" | "bind" | "toString")
574 && o.borrow().is_callable()
575 && !o.borrow().props.contains_key(key)
576 {
577 if let Some(r) = self.proto_chain_lookup(recv, o, key, Some(o.clone())) {
578 return r;
579 }
580 if let Some((n, f)) = super::super::builtins::function_method_fn(key) {
581 return Ok(self.builtin_fn_val(n, f));
582 }
583 }
584 if key == "caller" || key == "arguments" {
587 let b = o.borrow();
588 if let ObjKind::Function(fd) = &b.kind {
589 if !fd.shared.body.strict && !fd.is_arrow() && !b.props.contains_key(key) && !b.has_accessor(key) {
590 return Ok(Value::Undefined);
591 }
592 }
593 }
594 if key == "name" || key == "length" {
597 if let Some(v) = super::super::builtins::virtual_fn_prop_value(&o.borrow(), key) {
598 return Ok(v);
599 }
600 }
601 self.get_property_proto_chain(recv, o, key, Some(o.clone()))
602 }
603 }
604 }
605
606 pub(crate) fn get_property_proto_chain(
615 &mut self,
616 recv: &Value,
617 o: &ObjRef,
618 key: &str,
619 start: Option<ObjRef>,
620 ) -> EvalResult {
621 if let Some(r) = self.proto_chain_lookup(recv, o, key, start) {
628 return r;
629 }
630 if o.borrow().is_null_proto() {
637 return Ok(Value::Undefined);
638 }
639 if key == "constructor" {
643 let name = {
644 let b = o.borrow();
645 match &b.kind {
646 ObjKind::Array(_) => "Array",
647 ObjKind::PromiseObj(_) => "Promise",
648 ObjKind::MapObj(_) => "Map",
649 ObjKind::SetObj(_) => "Set",
650 ObjKind::RegExpObj(_) => "RegExp",
651 ObjKind::DateObj(_) => "Date",
652 _ if b.is_callable() => b.function_class_name(),
653 _ => "Object",
654 }
655 };
656 if let Some(c) = super::scope_get(&self.global, name) {
657 return Ok(c);
658 }
659 }
660 if (key == "name" || key == "length") && o.borrow().is_callable() && o.borrow().proto.is_none() {
662 if let Some(fp) = super::super::builtins::global_ctor_proto(self, o.borrow().function_class_name())
663 .or_else(|| super::super::builtins::global_ctor_proto(self, "Function"))
664 {
665 let b = fp.borrow();
666 if let Some(v) = b.props.get(key) {
667 return Ok(v.clone());
668 }
669 if let Some(v) = super::super::builtins::virtual_fn_prop_value(&b, key) {
670 return Ok(v);
671 }
672 }
673 }
674 Ok(self.object_get_prop(o, key))
676 }
677
678 pub(crate) fn proto_chain_lookup(
683 &mut self,
684 recv: &Value,
685 o: &ObjRef,
686 key: &str,
687 start: Option<ObjRef>,
688 ) -> Option<EvalResult> {
689 let mut cur_opt = start;
690 let mut guard = 0u32;
691 while let Some(cur) = cur_opt {
692 if !Rc::ptr_eq(&cur, o) && matches!(cur.borrow().kind, ObjKind::Proxy(_)) {
694 return Some(super::super::builtins::pm_get(self, &cur, key, recv));
695 }
696 if !Rc::ptr_eq(&cur, o) {
698 let hr = cur.borrow().kind.host_ref();
699 if let Some(h) = hr {
700 if let Some(v) = self.host_get(&cur, h, key) {
701 return Some(Ok(v));
702 }
703 }
704 }
705 let (getter_opt, prop_opt, next) = {
706 let b = cur.borrow();
707 if let Some(a) = b.get_accessor(key) {
708 (Some(a.get.clone()), None, None)
709 } else if let ObjKind::Array(items) = &b.kind {
710 if key == "length" {
711 (None, Some(Value::Number(items.len() as f64)), None)
712 } else if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
713 if idx < items.len() && !b.is_hole(idx) {
714 (None, Some(items[idx].clone()), None)
715 } else {
716 let next = match b.proto.clone() {
717 Some(p) => Some(p),
718 None => super::super::builtins::implicit_proto(self, &cur),
719 };
720 (None, None, next)
721 }
722 } else if let Some(v) = b.props.get(key) {
723 (None, Some(v.clone()), None)
724 } else {
725 let next = match b.proto.clone() {
726 Some(p) => Some(p),
727 None => super::super::builtins::implicit_proto(self, &cur),
728 };
729 (None, None, next)
730 }
731 } else if let Some(v) = b.props.get(key) {
732 (None, Some(v.clone()), None)
733 } else if (key == "name" || key == "length") && !Rc::ptr_eq(&cur, o) && b.has_virtual_fn_prop(key) {
734 (None, super::super::builtins::virtual_fn_prop_value(&b, key), None)
735 } else {
736 let next = match b.proto.clone() {
737 Some(p) => Some(p),
738 None => super::super::builtins::implicit_proto(self, &cur),
739 };
740 (None, None, next)
741 }
742 };
743 if let Some(getter) = getter_opt {
744 return Some(if let Some(g) = getter {
745 self.call_value(&g, recv.clone(), &[])
746 } else {
747 Ok(Value::Undefined)
748 });
749 }
750 if let Some(v) = prop_opt {
751 return Some(Ok(v));
752 }
753 guard += 1;
754 if guard > 1000 {
755 break;
756 }
757 cur_opt = next;
758 }
759 None
760 }
761
762 pub fn set_property(&mut self, recv: &Value, key: &str, val: Value) {
764 if let Err(e) = self.set_property_inner(recv, key, None, val) {
765 self.report_uncaught("setter", &e);
766 }
767 }
768
769 pub fn set_property_rc(&mut self, recv: &Value, key: &Rc<str>, val: Value) {
770 if let Err(e) = self.set_property_inner(recv, key, Some(key), val) {
771 self.report_uncaught("setter", &e);
772 }
773 }
774
775 #[inline]
778 pub fn put_value(&mut self, recv: &Value, key: &str, val: Value) -> Result<(), Value> {
779 match self.set_property_inner(recv, key, None, val) {
780 Ok(true) => Ok(()),
781 Ok(false) => self.put_failed(recv, key),
782 Err(e) => Err(e),
783 }
784 }
785
786 #[inline]
787 pub fn put_value_rc(&mut self, recv: &Value, key: &Rc<str>, val: Value) -> Result<(), Value> {
788 match self.set_property_inner(recv, key, Some(key), val) {
789 Ok(true) => Ok(()),
790 Ok(false) => self.put_failed(recv, key),
791 Err(e) => Err(e),
792 }
793 }
794
795 #[cold]
796 #[inline(never)]
797 fn put_failed(&mut self, recv: &Value, key: &str) -> Result<(), Value> {
798 if !self.strict {
799 return Ok(());
800 }
801 let what = match recv {
802 Value::Object(_) => "object",
803 _ => "primitive value",
804 };
805 Err(self.type_error(alloc::format!("Cannot assign to read only property '{}' of {}", key, what)))
806 }
807
808 pub(crate) fn set_property_inner(&mut self, recv: &Value, key: &str, key_rc: Option<&Rc<str>>, val: Value) -> Result<bool, Value> {
811 if let Value::Object(o) = recv {
812 {
817 let mut b = o.borrow_mut();
818 if !b.is_frozen()
819 && !b.is_sealed()
820 && !b.is_non_extensible()
821 && !b.has_rare_props()
822 && b.primitive().is_none()
823 && key != "__proto__"
824 && key != "returnValue"
825 && key != "cancelBubble"
826 && key != "selectedIndex"
827 {
828 if let ObjKind::Plain = b.kind {
829 if !b.props.contains_key("_is_location") && !proto_has_accessor(&b.proto, key) {
830 drop(b);
831 if !self.is_window_obj(o) {
832 let mut b = o.borrow_mut();
833 if let Some(slot) = b.props.get_mut(key) {
834 *slot = val;
835 } else {
836 let pk = match key_rc {
837 Some(rc) => rc.into(),
838 None => key.into(),
839 };
840 b.props.insert(pk, val);
841 }
842 return Ok(true);
843 }
844 }
845 } else if !b.props.contains_key("_ta_kind") && key != "length" {
846 if let ObjKind::Array(ref mut items) = b.kind {
847 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
848 if idx < items.len() {
849 items[idx] = val;
850 b.clear_hole(idx);
851 return Ok(true);
852 }
853 }
854 }
855 }
856 }
857 }
858
859 if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
861 return super::super::builtins::pm_set(self, o, key, val, recv);
862 }
863 if (key == "value" || key == "selectedIndex") && (self.host.special_set)(self, o, key, &val) {
865 return Ok(true);
866 }
867 let host_ref = o.borrow().kind.host_ref();
869 let val = match host_ref {
870 Some(h) => match (self.host.set)(self, o, h, key, val) {
871 None => return Ok(true),
872 Some(v) => v,
873 },
874 None => val,
875 };
876 if key == "returnValue" || key == "cancelBubble" {
883 let is_event = matches!(
884 o.borrow().props.get("preventDefault"),
885 Some(Value::Object(f)) if f.borrow().is_callable()
886 );
887 if is_event {
888 if key == "returnValue" && !val.truthy() {
889 let pd = o.borrow().props.get("preventDefault").cloned();
896 if let Some(f) = pd {
897 self.call_listener(&f, recv.clone(), &[], "preventDefault()");
898 }
899 return Ok(true);
900 }
901 if key == "cancelBubble" && val.truthy() {
902 let sp = o.borrow().props.get("stopPropagation").cloned();
903 if let Some(f) = sp {
904 self.call_listener(&f, recv.clone(), &[], "stopPropagation()");
905 }
906 return Ok(true);
907 }
908 let mut has_acc = false;
912 let mut cur_acc = Some(o.clone());
913 let mut g = 0u32;
914 while let Some(c) = cur_acc {
915 let b = c.borrow();
916 if b.has_accessor(key)
917 || matches!(b.kind, ObjKind::Proxy(_))
918 || (!alloc::rc::Rc::ptr_eq(&c, o)
919 && matches!(&b.kind, ObjKind::Bytes(_))
920 && b.props.contains_key("_ta_kind")
921 && crate::os_lib::ecma::value::is_canonical_numeric_key(key))
922 {
923 has_acc = true;
924 break;
925 }
926 g += 1;
927 if g > 64 {
928 break;
929 }
930 let p = b.proto.clone();
931 cur_acc = if p.is_none() && !b.is_null_proto() {
932 self.host_proto_of(&b.kind).flatten()
933 } else {
934 p
935 };
936 }
937 if !has_acc {
938 o.borrow_mut().props.insert(key.to_string().into(), val);
939 return Ok(true);
940 }
941 }
942 }
943 if matches!(o.borrow().kind, ObjKind::Bytes(_))
946 && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
947 {
948 let same_recv = matches!(recv, Value::Object(ro) if alloc::rc::Rc::ptr_eq(o, ro));
949 if !same_recv {
950 return super::super::builtins::set_on_receiver(self, key, val, recv);
951 }
952 if crate::os_lib::ecma::value::ta_is_immutable(&o.borrow()) {
953 return Ok(false);
954 }
955 let (st, is_bigint) = {
956 let b = o.borrow();
957 if let ObjKind::Bytes(st) = &b.kind {
958 (st.clone(), super::super::value::ByteStore::is_bigint_kind(st.raw_kind()))
959 } else {
960 unreachable!()
961 }
962 };
963 let coerced = if matches!(val, Value::Object(_)) {
964 self.to_primitive(val, "number")?
965 } else {
966 val
967 };
968 if coerced.type_of() == "symbol" {
969 return Err(self.type_error("Cannot convert a Symbol value to a number"));
970 }
971 let converted = if is_bigint {
972 match &coerced {
973 Value::BigInt(bi) => Value::BigInt(bi.clone()),
974 Value::Bool(true) => Value::bigint(super::super::bigint::BigInt::from_i64(1)),
975 Value::Bool(false) => Value::bigint(super::super::bigint::BigInt::zero()),
976 Value::Str(s) => match super::super::bigint::BigInt::parse_js_string(s) {
977 Some(bi) => Value::bigint(bi),
978 None => return Err(self.syntax_error("Cannot convert string to a BigInt")),
979 },
980 _ => return Err(self.type_error("Cannot convert value to a BigInt")),
981 }
982 } else {
983 if matches!(coerced, Value::BigInt(_)) {
984 return Err(self.type_error("Cannot convert a BigInt value to a number"));
985 }
986 coerced
987 };
988 let valid_idx = crate::os_lib::ecma::value::ta_valid_index(&o.borrow(), key);
990 if let Some(idx) = valid_idx {
991 st.set_value(idx, &converted);
992 }
993 return Ok(true);
994 }
995 if matches!(o.borrow().kind, ObjKind::Bytes(_)) && key == "length" {
996 return Ok(false);
997 }
998 let mut cur = o.clone();
1004 let mut guard = 0u32;
1007 loop {
1008 if matches!(cur.borrow().kind, ObjKind::Proxy(_)) {
1009 return super::super::builtins::pm_set(self, &cur, key, val, recv);
1010 }
1011 if !alloc::rc::Rc::ptr_eq(&cur, o)
1012 && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
1013 {
1014 let is_ta_proto = {
1015 let cb = cur.borrow();
1016 matches!(&cb.kind, ObjKind::Bytes(_)) && cb.props.contains_key("_ta_kind")
1017 };
1018 if is_ta_proto {
1019 return Ok(true);
1022 }
1023 }
1024 let (has_accessor_entry, has_own_data) = {
1025 let cb = cur.borrow();
1026 let is_arr_len = matches!(&cb.kind, ObjKind::Array(_)) && key == "length";
1027 let is_arr_elem = matches!(&cb.kind, ObjKind::Array(items)
1028 if !cb.props.contains_key("_ta_kind")
1029 && crate::os_lib::ecma::value::parse_index(key)
1030 .is_some_and(|i| i < items.len() && !cb.is_hole(i)));
1031 (cb.has_accessor(key), cb.props.contains_key(key) || is_arr_len || is_arr_elem)
1032 };
1033 if has_accessor_entry {
1034 let setter = cur.borrow().get_setter(key);
1035 if let Some(s) = setter {
1036 self.call_value(&s, recv.clone(), &[val])?;
1037 return Ok(true);
1038 }
1039 return Ok(false);
1042 }
1043 if has_own_data {
1044 break;
1045 }
1046 guard += 1;
1047 if guard > 1000 {
1048 break;
1049 }
1050 let next = {
1051 let cb = cur.borrow();
1052 match cb.proto.clone() {
1053 Some(p) => Some(p),
1054 None if !cb.is_null_proto() => super::super::builtins::implicit_proto(self, &cur),
1055 None => None,
1056 }
1057 };
1058 match next {
1059 Some(p) if !alloc::rc::Rc::ptr_eq(&p, &cur) => cur = p,
1060 _ => break,
1061 }
1062 }
1063 let mut b = o.borrow_mut();
1064 if b.is_frozen() {
1065 return Ok(false);
1066 }
1067 if let Some(Value::Str(sv)) = b.primitive() {
1068 if !super::super::builtins::is_symbol_like_key(sv)
1069 && (key == "length"
1070 || crate::os_lib::ecma::value::parse_index(key)
1071 .is_some_and(|i| i < sv.encode_utf16().count()))
1072 {
1073 return Ok(false);
1074 }
1075 }
1076 if b.props.contains_key(key) {
1077 if let Some(attr) = b.get_attr(key) {
1078 if !attr.writable {
1079 return Ok(false);
1080 }
1081 }
1082 } else if !b.has_accessor(key) && b.has_virtual_fn_prop(key) {
1083 return Ok(false);
1085 }
1086 let ta_kind_tag = b.props.get("_ta_kind").map(|v| v.to_js_string());
1092 if matches!(b.kind, ObjKind::Array(_)) {
1093 if !b.props.contains_key("_ta_kind") {
1097 if key == "length" {
1098 if b.get_attr("length").is_some_and(|a| !a.writable) {
1099 return Ok(false);
1100 }
1101 } else if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1102 let cur = match &b.kind {
1103 ObjKind::Array(items) => items.len(),
1104 _ => 0,
1105 };
1106 if idx < cur {
1107 if b.get_attr(key).is_some_and(|a| !a.writable) {
1108 return Ok(false);
1109 }
1110 } else if b.is_sealed()
1111 || b.is_non_extensible()
1112 || b.get_attr("length").is_some_and(|a| !a.writable)
1113 {
1114 return Ok(false);
1115 }
1116 }
1117 }
1118 if key == "length" {
1119 let n = val.to_number();
1120 if n.is_finite() && n >= 0.0 {
1121 let n = n as usize;
1122 let cur = match &b.kind {
1123 ObjKind::Array(items) => items.len(),
1124 _ => 0,
1125 };
1126 if n > cur {
1127 b.grow_array(n);
1129 } else if let ObjKind::Array(items) = &mut b.kind {
1130 items.truncate(n);
1131 }
1132 }
1133 return Ok(true);
1134 }
1135 let index = crate::os_lib::ecma::value::parse_index(key);
1137 if let Some(idx) = index {
1138 let cur = match &b.kind {
1139 ObjKind::Array(items) => items.len(),
1140 _ => 0,
1141 };
1142 if idx >= cur && !b.grow_array(idx + 1) {
1143 b.props.insert(key.into(), val);
1145 return Ok(true);
1146 }
1147 b.clear_hole(idx);
1148 }
1149 }
1150 if let ObjKind::Array(items) = &mut b.kind {
1151 if let Some(idx) = crate::os_lib::ecma::value::parse_index(key).filter(|&i| i < items.len()) {
1152 let val = match &ta_kind_tag {
1153 Some(tag) => Value::Number(super::super::builtins::ta_coerce_index_value(tag, &val)),
1154 None => val,
1155 };
1156 items[idx] = val;
1157 if ta_kind_tag.is_some() && b.props.contains_key("_view_root") {
1159 drop(b);
1160 super::super::builtins::ta_write_through(o, idx, idx + 1);
1161 }
1162 return Ok(true);
1163 }
1164 }
1165 if (b.is_sealed() || b.is_non_extensible()) && !b.props.contains_key(key) {
1168 return Ok(false);
1169 }
1170 let is_location = b.props.contains_key("_is_location");
1175 if is_location {
1176 let new_val = val.to_js_string();
1177 if matches!(key, "href" | "hash" | "pathname" | "search" | "protocol" | "host" | "hostname" | "port") {
1179 let top = self.call_stack_names(8);
1180 crate::warn!("[JSNAV] location.{} = {:?} top={:?}", key, new_val.chars().take(120).collect::<String>(), top);
1181 }
1182 match key {
1183 "href" => {
1184 b.props
1185 .insert(String::from("_pending_location").into(), Value::str(&new_val));
1186 b.props
1187 .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1188 }
1189 "hash" => {
1190 let cur = b
1192 .props
1193 .get("href")
1194 .map(|v| v.to_js_string())
1195 .unwrap_or_default();
1196 let base = match cur.split_once('#') {
1197 Some((b, _)) => String::from(b),
1198 None => cur,
1199 };
1200 let frag = new_val.trim_start_matches('#');
1201 let full = alloc::format!("{}#{}", base, frag);
1202 b.props
1203 .insert(String::from("_pending_location").into(), Value::str(&full));
1204 b.props
1205 .insert(String::from("_pending_location_mode").into(), Value::str("hash"));
1206 }
1207 "pathname" | "search" => {
1208 let proto = b
1210 .props
1211 .get("protocol")
1212 .map(|v| v.to_js_string())
1213 .unwrap_or_else(|| String::from("https:"));
1214 let host = b
1215 .props
1216 .get("host")
1217 .map(|v| v.to_js_string())
1218 .unwrap_or_default();
1219 let pathname = if key == "pathname" {
1220 new_val.clone()
1221 } else {
1222 b.props
1223 .get("pathname")
1224 .map(|v| v.to_js_string())
1225 .unwrap_or_else(|| String::from("/"))
1226 };
1227 let search = if key == "search" {
1228 if new_val.is_empty() || new_val.starts_with('?') {
1229 new_val.clone()
1230 } else {
1231 alloc::format!("?{}", new_val)
1232 }
1233 } else {
1234 b.props
1235 .get("search")
1236 .map(|v| v.to_js_string())
1237 .unwrap_or_default()
1238 };
1239 let full = alloc::format!("{}//{}{}{}", proto, host, pathname, search);
1240 b.props
1241 .insert(String::from("_pending_location").into(), Value::str(&full));
1242 b.props
1243 .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1244 }
1245 "protocol" | "host" | "hostname" | "port" => {
1254 let proto = if key == "protocol" {
1255 if new_val.ends_with(':') { new_val.clone() } else { alloc::format!("{}:", new_val) }
1256 } else {
1257 b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_else(|| String::from("https:"))
1258 };
1259 let host = if key == "host" {
1260 let (hn, pt) = match new_val.split_once(':') {
1265 Some((h, p)) => (String::from(h), String::from(p)),
1266 None => (new_val.clone(), String::new()),
1267 };
1268 b.props.insert(String::from("hostname").into(), Value::str(&hn));
1269 b.props.insert(String::from("port").into(), Value::str(&pt));
1270 new_val.clone()
1271 } else if key == "hostname" || key == "port" {
1272 let hostname = if key == "hostname" {
1273 new_val.clone()
1274 } else {
1275 b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_default()
1276 };
1277 let port = if key == "port" {
1278 new_val.clone()
1279 } else {
1280 b.props.get("port").map(|v| v.to_js_string()).unwrap_or_default()
1281 };
1282 if port.is_empty() { hostname } else { alloc::format!("{}:{}", hostname, port) }
1283 } else {
1284 b.props.get("host").map(|v| v.to_js_string()).unwrap_or_default()
1285 };
1286 let pathname = b
1287 .props
1288 .get("pathname")
1289 .map(|v| v.to_js_string())
1290 .unwrap_or_else(|| String::from("/"));
1291 let search = b.props.get("search").map(|v| v.to_js_string()).unwrap_or_default();
1292 let full = alloc::format!("{}//{}{}{}", proto, host, pathname, search);
1293 b.props
1294 .insert(String::from("_pending_location").into(), Value::str(&full));
1295 b.props
1296 .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1297 }
1298 _ => {}
1299 }
1300 if let Some(slot) = b.props.get_mut(key) {
1302 *slot = val;
1303 } else {
1304 let pk = match key_rc {
1305 Some(rc) => rc.into(),
1306 None => key.into(),
1307 };
1308 b.props.insert(pk, val);
1309 }
1310 return Ok(true);
1311 }
1312 let is_win = self.is_window_obj(o);
1313 let win_val = if is_win { Some(val.clone()) } else { None };
1314 if let Some(slot) = b.props.get_mut(key) {
1315 *slot = val;
1316 } else {
1317 let pk = match key_rc {
1318 Some(rc) => rc.into(),
1319 None => key.into(),
1320 };
1321 b.props.insert(pk, val);
1322 }
1323 drop(b);
1324 if let Some(v) = win_val {
1327 if !self.global_lexicals.borrow().contains(key) {
1328 if let Some(slot) = self.global.borrow_mut().vars.get_mut(key) {
1329 *slot = v;
1330 }
1331 }
1332 }
1333 } else {
1334 return self.set_on_primitive(recv, key, val);
1335 }
1336 Ok(true)
1337 }
1338
1339 #[cold]
1342 #[inline(never)]
1343 fn set_on_primitive(&mut self, recv: &Value, key: &str, val: Value) -> Result<bool, Value> {
1344 let ctor = match recv {
1345 Value::Str(_) => "String",
1346 Value::Number(_) => "Number",
1347 Value::Bool(_) => "Boolean",
1348 Value::BigInt(_) => "BigInt",
1349 _ => return Ok(false),
1350 };
1351 let mut cur = super::super::builtins::global_ctor_proto(self, ctor);
1352 let mut guard = 0u32;
1353 while let Some(p) = cur {
1354 let setter = {
1355 let b = p.borrow();
1356 if b.has_accessor(key) {
1357 Some(b.get_setter(key))
1358 } else if b.props.contains_key(key) {
1359 return Ok(false);
1360 } else {
1361 None
1362 }
1363 };
1364 if let Some(s) = setter {
1365 return match s {
1366 Some(f) => {
1367 self.call_value(&f, recv.clone(), &[val])?;
1368 Ok(true)
1369 }
1370 None => Ok(false),
1371 };
1372 }
1373 guard += 1;
1374 if guard > 100 {
1375 break;
1376 }
1377 cur = p.borrow().proto.clone();
1378 }
1379 Ok(false)
1380 }
1381
1382 }
1385
1386#[inline]
1387fn proto_has_accessor(proto: &Option<ObjRef>, key: &str) -> bool {
1388 let mut cur = proto.clone();
1389 let mut guard = 0u32;
1390 while let Some(p) = cur {
1391 let Ok(b) = p.try_borrow() else {
1392 return true;
1393 };
1394 if b.has_accessor(key)
1395 || matches!(b.kind, ObjKind::Proxy(_))
1396 || (matches!(&b.kind, ObjKind::Bytes(_))
1397 && b.props.contains_key("_ta_kind")
1398 && crate::os_lib::ecma::value::is_canonical_numeric_key(key))
1399 {
1400 return true;
1401 }
1402 guard += 1;
1403 if guard > 64 {
1404 return true;
1405 }
1406 cur = b.proto.clone();
1407 }
1408 false
1409}
1410
1411pub(crate) fn describe_expr(e: &crate::os_lib::ecma::ast::Expression) -> String {
1413 use crate::os_lib::ecma::ast::Expression as E;
1414 let s = match e {
1415 E::Identifier(n) => n.to_string(),
1416 E::This => String::from("this"),
1417 E::Member { object, property, .. } => alloc::format!("{}.{}", describe_expr(object), property),
1418 E::Index { object, .. } => alloc::format!("{}[…]", describe_expr(object)),
1419 E::Call { callee, .. } => alloc::format!("{}()", describe_expr(callee)),
1420 E::Assign { op, target, value } => alloc::format!("({}{}{})", describe_expr(target), op, describe_expr(value)),
1422 E::Logical { left, right, .. } => alloc::format!("({}||&&{})", describe_expr(left), describe_expr(right)),
1423 E::Conditional { consequent, alternate, .. } => alloc::format!("(…?{}:{})", describe_expr(consequent), describe_expr(alternate)),
1424 E::Sequence(v) => match v.last() {
1425 Some(l) => alloc::format!("(…,{})", describe_expr(l)),
1426 None => String::from("…"),
1427 },
1428 _ => String::from("…"),
1429 };
1430 if s.chars().count() > 80 {
1431 let t: String = s.chars().rev().take(80).collect::<Vec<_>>().into_iter().rev().collect();
1432 alloc::format!("…{t}")
1433 } else {
1434 s
1435 }
1436}