1use crate::host::{self, with_host, JsObj};
20use fusevm::Value;
21
22pub fn parts(v: &Value) -> Option<(Value, Value)> {
24 with_host(|h| match h.get(v) {
25 Some(JsObj::Proxy {
26 target, handler, ..
27 }) => Some((target.clone(), handler.clone())),
28 _ => None,
29 })
30}
31
32fn revoked(v: &Value) -> bool {
34 with_host(|h| matches!(h.get(v), Some(JsObj::Proxy { revoked, .. }) if *revoked))
35}
36
37pub fn ultimate_target(v: &Value) -> Option<Value> {
41 let mut cur = parts(v)?.0;
42 for _ in 0..100 {
43 match parts(&cur) {
44 Some((t, _)) => cur = t,
45 None => return Some(cur),
46 }
47 }
48 Some(cur)
49}
50
51pub fn is_array_subject(v: &Value) -> Result<Value, String> {
54 subject_through(v, "IsArray")
55}
56
57pub fn require_live(v: &Value, op: &str) -> Result<(), String> {
60 subject_through(v, op).map(|_| ())
61}
62
63fn subject_through(v: &Value, op: &str) -> Result<Value, String> {
64 let mut cur = v.clone();
65 while let Some((target, _)) = parts(&cur) {
66 if revoked(&cur) {
67 return Err(revoked_err(op));
68 }
69 cur = target;
70 }
71 Ok(cur)
72}
73
74fn revoked_err(op: &str) -> String {
76 host::type_error(&format!(
77 "Cannot perform '{op}' on a proxy that has been revoked"
78 ))
79}
80
81pub fn has_trap(v: &Value, name: &str) -> bool {
94 matches!(trap(v, name), Ok(Some(_)))
95}
96
97fn trap(v: &Value, name: &str) -> Result<Option<(Value, Value, Value)>, String> {
98 let Some((target, handler)) = parts(v) else {
99 return Ok(None);
100 };
101 if revoked(v) {
102 return Err(revoked_err(name));
103 }
104 let t = crate::builtins::get_property(&handler, name)?;
105 if matches!(t, Value::Undef) || with_host(|h| h.is_null(&t)) {
106 return Ok(None);
107 }
108 if !with_host(|h| host::is_callable(h, &t)) {
109 return Err(host::type_error(&format!(
110 "'{}' returned for property '{name}' of object '#<Object>' is not a function",
111 with_host(|h| h.str_of(&t))
112 )));
113 }
114 Ok(Some((t, target, handler)))
115}
116
117fn no_trap(v: &Value, op: &str) -> Result<Option<Value>, String> {
120 match parts(v) {
121 None => Ok(None),
122 Some((target, _)) if !revoked(v) => Ok(Some(target)),
123 Some(_) => Err(revoked_err(op)),
124 }
125}
126
127pub fn key_value(k: &str) -> Value {
131 with_host(|h| {
132 if let Some(s) = h.symbol_of_key(k) {
133 return s;
134 }
135 match k.strip_prefix("@@") {
136 Some(name) if host::WELL_KNOWN_SYMBOLS.contains(&name) => h.well_known_symbol(name),
137 _ => h.new_str(k),
138 }
139 })
140}
141
142fn call(t: &Value, handler: &Value, args: Vec<Value>) -> Result<Value, String> {
143 host::invoke(t, args, Some(handler.clone()))
144}
145
146fn invariant(msg: &str) -> String {
158 host::type_error(msg)
159}
160
161fn shown(v: &Value) -> String {
163 crate::builtins::no_side_effects_string_pub(v)
164}
165
166#[derive(Default)]
168struct Desc {
169 value: Option<Value>,
170 writable: Option<bool>,
171 get: Option<Value>,
172 set: Option<Value>,
173 enumerable: Option<bool>,
174 configurable: Option<bool>,
175}
176
177impl Desc {
178 fn is_accessor(&self) -> bool {
179 self.get.is_some() || self.set.is_some()
180 }
181 fn is_data(&self) -> bool {
182 self.value.is_some() || self.writable.is_some()
183 }
184 fn is_generic(&self) -> bool {
185 !self.is_accessor() && !self.is_data()
186 }
187 fn is_empty(&self) -> bool {
188 self.is_generic() && self.enumerable.is_none() && self.configurable.is_none()
189 }
190
191 fn from_object(obj: &Value) -> Result<Desc, String> {
194 if !with_host(|h| {
195 matches!(obj, Value::Obj(_)) && !h.is_null(obj) && !host::is_primitive(h, obj)
196 }) {
197 return Err(host::type_error(&format!(
198 "Property description must be an object: {}",
199 shown(obj)
200 )));
201 }
202 let field = |k: &str| -> Result<Option<Value>, String> {
203 if crate::builtins::has_property(obj, k)? {
204 crate::builtins::get_property(obj, k).map(Some)
205 } else {
206 Ok(None)
207 }
208 };
209 let truthy = |v: Value| with_host(|h| h.truthy(&v));
210 let mut d = Desc {
211 enumerable: field("enumerable")?.map(truthy),
212 configurable: field("configurable")?.map(truthy),
213 value: field("value")?,
214 writable: field("writable")?.map(truthy),
215 ..Desc::default()
216 };
217 for (k, slot, what) in [("get", &mut d.get, "Getter"), ("set", &mut d.set, "Setter")] {
218 if let Some(f) = field(k)? {
219 if !matches!(f, Value::Undef) && !with_host(|h| host::is_callable(h, &f)) {
220 return Err(host::type_error(&format!(
221 "{what} must be a function: {}",
222 shown(&f)
223 )));
224 }
225 *slot = Some(f);
226 }
227 }
228 if d.is_accessor() && d.is_data() {
229 return Err(host::type_error(&format!(
230 "Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, {}",
231 shown(obj)
232 )));
233 }
234 Ok(d)
235 }
236
237 fn complete(mut self) -> Desc {
239 if self.is_generic() || self.is_data() {
240 self.value.get_or_insert(Value::Undef);
241 self.writable.get_or_insert(false);
242 } else {
243 self.get.get_or_insert(Value::Undef);
244 self.set.get_or_insert(Value::Undef);
245 }
246 self.enumerable.get_or_insert(false);
247 self.configurable.get_or_insert(false);
248 self
249 }
250
251 fn to_object(&self) -> Value {
254 let mut m = indexmap::IndexMap::new();
255 if let Some(v) = &self.value {
256 m.insert("value".to_string(), v.clone());
257 }
258 if let Some(w) = self.writable {
259 m.insert("writable".to_string(), Value::Bool(w));
260 }
261 if let Some(g) = &self.get {
262 m.insert("get".to_string(), g.clone());
263 }
264 if let Some(s) = &self.set {
265 m.insert("set".to_string(), s.clone());
266 }
267 if let Some(e) = self.enumerable {
268 m.insert("enumerable".to_string(), Value::Bool(e));
269 }
270 if let Some(c) = self.configurable {
271 m.insert("configurable".to_string(), Value::Bool(c));
272 }
273 with_host(|h| h.new_object(m))
274 }
275}
276
277fn target_desc(target: &Value, key: &str) -> Result<Option<Desc>, String> {
280 let d = crate::builtins::own_descriptor_pub(target, key_value(key))?;
281 if matches!(d, Value::Undef) {
282 return Ok(None);
283 }
284 Desc::from_object(&d).map(Some)
285}
286
287fn target_extensible(target: &Value) -> Result<bool, String> {
289 match is_extensible(target)? {
290 Some(b) => Ok(b),
291 None => Ok(with_host(|h| h.is_extensible(target))),
292 }
293}
294
295fn is_compatible(extensible: bool, desc: &Desc, current: Option<&Desc>) -> bool {
298 let Some(current) = current else {
299 return extensible;
300 };
301 if desc.is_empty() || current.configurable != Some(false) {
302 return true;
303 }
304 if desc.configurable == Some(true) {
305 return false;
306 }
307 if desc.enumerable.is_some() && desc.enumerable != current.enumerable {
308 return false;
309 }
310 if !desc.is_generic() && desc.is_accessor() != current.is_accessor() {
311 return false;
312 }
313 let differs = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
314 (Some(x), Some(y)) => !crate::builtins::same_value(x, y),
315 (Some(x), None) => !matches!(x, Value::Undef),
316 _ => false,
317 };
318 if current.is_accessor() {
319 return !differs(&desc.get, ¤t.get) && !differs(&desc.set, ¤t.set);
320 }
321 if current.writable == Some(false) {
322 return desc.writable != Some(true) && !differs(&desc.value, ¤t.value);
323 }
324 true
325}
326
327pub fn get(v: &Value, key: &str, receiver: &Value) -> Result<Option<Value>, String> {
328 if let Some((t, target, handler)) = trap(v, "get")? {
329 let k = key_value(key);
330 let got = call(&t, &handler, vec![target.clone(), k, receiver.clone()])?;
331 if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
335 if d.is_data() && d.writable == Some(false) {
336 let val = d.value.clone().unwrap_or(Value::Undef);
337 if !crate::builtins::same_value(&got, &val) {
338 return Err(invariant(&format!(
339 "'get' on proxy: property '{key}' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '{}' but got '{}')",
340 shown(&val),
341 shown(&got)
342 )));
343 }
344 }
345 if d.is_accessor()
346 && matches!(d.get, Some(Value::Undef) | None)
347 && !matches!(got, Value::Undef)
348 {
349 return Err(invariant(&format!(
350 "'get' on proxy: property '{key}' is a non-configurable accessor property on the proxy target and does not have a getter function, but the trap did not return 'undefined' (got '{}')",
351 shown(&got)
352 )));
353 }
354 }
355 return Ok(Some(got));
356 }
357 match no_trap(v, "get")? {
358 Some(target) => crate::builtins::get_property_recv(&target, key, receiver).map(Some),
359 None => Ok(None),
360 }
361}
362
363pub fn set(v: &Value, key: &str, val: &Value, receiver: &Value) -> Result<bool, String> {
365 if let Some((t, target, handler)) = trap(v, "set")? {
366 let k = key_value(key);
367 let r = call(
368 &t,
369 &handler,
370 vec![target.clone(), k, val.clone(), receiver.clone()],
371 )?;
372 if !with_host(|h| h.truthy(&r)) {
378 return Ok(false);
379 }
380 if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
384 if d.is_data()
385 && d.writable == Some(false)
386 && !crate::builtins::same_value(val, d.value.as_ref().unwrap_or(&Value::Undef))
387 {
388 return Err(invariant(&format!(
389 "'set' on proxy: trap returned truish for property '{key}' which exists in the proxy target as a non-configurable and non-writable data property with a different value"
390 )));
391 }
392 if d.is_accessor() && matches!(d.set, Some(Value::Undef) | None) {
393 return Err(invariant(&format!(
394 "'set' on proxy: trap returned truish for property '{key}' which exists in the proxy target as a non-configurable and non-writable accessor property without a setter"
395 )));
396 }
397 }
398 return Ok(true);
399 }
400 match no_trap(v, "set")? {
401 Some(target) => {
402 if receiver_observes_set(v, &target, key, receiver) {
403 return define_on_proxy_receiver(v, key, val);
404 }
405 crate::builtins::set_property_pub(&target, key, val.clone())?;
406 Ok(true)
407 }
408 None => Ok(false),
409 }
410}
411
412fn receiver_observes_set(v: &Value, target: &Value, key: &str, receiver: &Value) -> bool {
423 with_host(|h| h.strict_eq(receiver, v))
424 && (has_trap(v, "getOwnPropertyDescriptor") || has_trap(v, "defineProperty"))
425 && parts(target).is_none()
426 && with_host(|h| {
427 host::lookup_accessor(h, target, key).is_none() && h.can_write_prop(target, key)
428 })
429}
430
431fn define_on_proxy_receiver(v: &Value, key: &str, val: &Value) -> Result<bool, String> {
438 let existing = get_own_descriptor(v, key)?.unwrap_or(Value::Undef);
439 let mut desc = indexmap::IndexMap::new();
440 desc.insert("value".to_string(), val.clone());
441 if !matches!(existing, Value::Undef) {
442 let field = |n: &str| crate::builtins::get_property(&existing, n);
443 let is_accessor = with_host(|h| {
444 host::lookup_chain(h, &existing, "get").is_some()
445 || host::lookup_chain(h, &existing, "set").is_some()
446 });
447 let writable = field("writable")?;
448 if is_accessor || !with_host(|h| h.truthy(&writable)) {
449 return Ok(false);
450 }
451 } else {
452 for flag in ["writable", "enumerable", "configurable"] {
453 desc.insert(flag.to_string(), Value::Bool(true));
454 }
455 }
456 let desc = with_host(|h| h.new_object(desc));
457 if define_property(v, key, &desc)? {
458 return Ok(true);
459 }
460 if with_host(|h| h.current_strict()) {
461 return Err(host::type_error(&format!(
462 "'defineProperty' on proxy: trap returned falsish for property '{key}'"
463 )));
464 }
465 Ok(false)
466}
467
468pub fn has(v: &Value, key: &str) -> Result<Option<bool>, String> {
470 if let Some((t, target, handler)) = trap(v, "has")? {
471 let k = key_value(key);
472 let r = call(&t, &handler, vec![target.clone(), k])?;
473 let reported = with_host(|h| h.truthy(&r));
474 if !reported {
477 if let Some(d) = target_desc(&target, key)? {
478 if d.configurable == Some(false) {
479 return Err(invariant(&format!(
480 "'has' on proxy: trap returned falsish for property '{key}' which exists in the proxy target as non-configurable"
481 )));
482 }
483 if !target_extensible(&target)? {
484 return Err(invariant(&format!(
485 "'has' on proxy: trap returned falsish for property '{key}' but the proxy target is not extensible"
486 )));
487 }
488 }
489 }
490 return Ok(Some(reported));
491 }
492 match no_trap(v, "has")? {
493 Some(target) => crate::builtins::has_property(&target, key).map(Some),
494 None => Ok(None),
495 }
496}
497
498pub fn delete(v: &Value, key: &str) -> Result<Option<bool>, String> {
500 if let Some((t, target, handler)) = trap(v, "deleteProperty")? {
501 let k = key_value(key);
502 let r = call(&t, &handler, vec![target.clone(), k])?;
503 let reported = with_host(|h| h.truthy(&r));
504 if reported {
507 if let Some(d) = target_desc(&target, key)? {
508 if d.configurable == Some(false) {
509 return Err(invariant(&format!(
510 "'deleteProperty' on proxy: trap returned truish for property '{key}' which is non-configurable in the proxy target"
511 )));
512 }
513 if !target_extensible(&target)? {
514 return Err(invariant(&format!(
515 "'deleteProperty' on proxy: trap returned truish for property '{key}' but the proxy target is non-extensible"
516 )));
517 }
518 }
519 }
520 return Ok(Some(reported));
521 }
522 match no_trap(v, "deleteProperty")? {
523 Some(target) => crate::builtins::delete_property(&target, key).map(Some),
524 None => Ok(None),
525 }
526}
527
528pub fn own_keys(v: &Value) -> Result<Option<Vec<String>>, String> {
531 if let Some((t, target, handler)) = trap(v, "ownKeys")? {
532 let r = call(&t, &handler, vec![target.clone()])?;
533 if !with_host(|h| {
536 matches!(r, Value::Obj(_)) && !h.is_null(&r) && !host::is_primitive(h, &r)
537 }) {
538 return Err(host::type_error(
539 "CreateListFromArrayLike called on non-object",
540 ));
541 }
542 let len = crate::builtins::length_of_array_like(&r)?;
543 let mut out = Vec::with_capacity(len);
544 for i in 0..len {
545 let k = crate::builtins::get_property(&r, &i.to_string())?;
546 let is_key = with_host(|h| {
547 h.as_str(&k).is_some() || matches!(h.get(&k), Some(JsObj::Symbol { .. }))
548 });
549 if !is_key {
550 return Err(host::type_error(&format!(
551 "{} is not a valid property name",
552 shown(&k)
553 )));
554 }
555 out.push(host::to_property_key(&k)?);
556 }
557 let mut seen: Vec<&String> = Vec::with_capacity(out.len());
559 for k in &out {
560 if seen.contains(&k) {
561 return Err(invariant(
562 "'ownKeys' on proxy: trap returned duplicate entries",
563 ));
564 }
565 seen.push(k);
566 }
567 let target_keys = with_host(|h| {
569 let mut ks = h.own_key_names(&target, false);
570 ks.extend(
571 h.own_symbol_keys(&target)
572 .iter()
573 .map(|sym| h.property_key(sym))
574 .collect::<Vec<_>>(),
575 );
576 ks
577 });
578 for k in &target_keys {
579 let pinned =
580 crate::builtins::own_prop_facts(&target, k).is_some_and(|(_, _, conf, _)| !conf);
581 if pinned && !out.contains(k) {
582 return Err(invariant(&format!(
583 "'ownKeys' on proxy: trap result did not include '{k}'"
584 )));
585 }
586 }
587 if !with_host(|h| h.is_extensible(&target)) {
589 for k in &target_keys {
590 if !out.contains(k) {
591 return Err(invariant(&format!(
592 "'ownKeys' on proxy: trap result did not include '{k}'"
593 )));
594 }
595 }
596 for k in &out {
597 if !target_keys.contains(k) {
598 return Err(invariant(
599 "'ownKeys' on proxy: trap returned extra keys but proxy target is non-extensible",
600 ));
601 }
602 }
603 }
604 return Ok(Some(out));
605 }
606 match no_trap(v, "ownKeys")? {
607 Some(target) => {
608 let mut keys = with_host(|h| h.own_key_names(&target, false));
609 keys.extend(with_host(|h| {
610 h.own_symbol_keys(&target)
611 .iter()
612 .map(|s| h.property_key(s))
613 .collect::<Vec<_>>()
614 }));
615 Ok(Some(keys))
616 }
617 None => Ok(None),
618 }
619}
620
621pub fn get_own_descriptor(v: &Value, key: &str) -> Result<Option<Value>, String> {
623 if let Some((t, target, handler)) = trap(v, "getOwnPropertyDescriptor")? {
624 let k = key_value(key);
625 let d = call(&t, &handler, vec![target.clone(), k])?;
626 return checked_own_descriptor(&target, key, &d).map(Some);
627 }
628 match no_trap(v, "getOwnPropertyDescriptor")? {
629 Some(target) => {
630 let k = key_value(key);
631 crate::builtins::own_descriptor_pub(&target, k).map(Some)
632 }
633 None => Ok(None),
634 }
635}
636
637fn checked_own_descriptor(target: &Value, key: &str, d: &Value) -> Result<Value, String> {
641 let is_object =
642 with_host(|h| matches!(d, Value::Obj(_)) && !h.is_null(d) && !host::is_primitive(h, d));
643 if !is_object && !matches!(d, Value::Undef) {
644 return Err(invariant(&format!(
645 "'getOwnPropertyDescriptor' on proxy: trap returned neither object nor undefined for property '{key}'"
646 )));
647 }
648 let target_d = target_desc(target, key)?;
649 if !is_object {
650 if let Some(td) = &target_d {
651 if td.configurable == Some(false) {
652 return Err(invariant(&format!(
653 "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which is non-configurable in the proxy target"
654 )));
655 }
656 if !target_extensible(target)? {
657 return Err(invariant(&format!(
658 "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which exists in the non-extensible proxy target"
659 )));
660 }
661 }
662 return Ok(Value::Undef);
663 }
664 let extensible = target_extensible(target)?;
665 let result = Desc::from_object(d)?.complete();
666 if !is_compatible(extensible, &result, target_d.as_ref()) {
667 return Err(invariant(&format!(
668 "'getOwnPropertyDescriptor' on proxy: trap returned descriptor for property '{key}' that is incompatible with the existing property in the proxy target"
669 )));
670 }
671 if result.configurable == Some(false) {
672 match &target_d {
673 Some(td) if td.configurable == Some(false) => {
674 if result.writable == Some(false) && td.writable == Some(true) {
675 return Err(invariant(&format!(
676 "'getOwnPropertyDescriptor' on proxy: trap reported non-configurable and non-writable for property '{key}' which is non-configurable, writable in the proxy target"
677 )));
678 }
679 }
680 _ => {
681 return Err(invariant(&format!(
682 "'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for property '{key}' which is either non-existent or configurable in the proxy target"
683 )));
684 }
685 }
686 }
687 Ok(result.to_object())
688}
689
690pub fn define_property(v: &Value, key: &str, desc: &Value) -> Result<bool, String> {
693 if let Some((t, target, handler)) = trap(v, "defineProperty")? {
694 let k = key_value(key);
695 let d = Desc::from_object(desc)?;
696 let r = call(&t, &handler, vec![target.clone(), k, d.to_object()])?;
697 if !with_host(|h| h.truthy(&r)) {
703 return Ok(false);
704 }
705 let target_d = target_desc(&target, key)?;
708 let extensible = target_extensible(&target)?;
709 let setting_config_false = d.configurable == Some(false);
710 let non_configurable = || {
711 invariant(&format!(
712 "'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which is either non-existent or configurable in the proxy target"
713 ))
714 };
715 match &target_d {
716 None => {
717 if !extensible {
718 return Err(invariant(&format!(
719 "'defineProperty' on proxy: trap returned truish for adding property '{key}' to the non-extensible proxy target"
720 )));
721 }
722 if setting_config_false {
723 return Err(non_configurable());
724 }
725 }
726 Some(td) => {
727 if !is_compatible(extensible, &d, Some(td)) {
728 return Err(invariant(&format!(
729 "'defineProperty' on proxy: trap returned truish for adding property '{key}' that is incompatible with the existing property in the proxy target"
730 )));
731 }
732 if setting_config_false && td.configurable == Some(true) {
733 return Err(non_configurable());
734 }
735 if td.is_data()
736 && td.configurable == Some(false)
737 && td.writable == Some(true)
738 && d.writable == Some(false)
739 {
740 return Err(invariant(&format!(
741 "'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which cannot be non-writable, unless there exists a corresponding non-configurable, non-writable own property of the target object."
742 )));
743 }
744 }
745 }
746 return Ok(true);
747 }
748 match no_trap(v, "defineProperty")? {
749 Some(target) => {
750 let k = key_value(key);
751 crate::builtins::define_property_pub(&target, k, desc.clone())?;
752 Ok(true)
753 }
754 None => Ok(false),
755 }
756}
757
758pub fn get_prototype_of(v: &Value) -> Result<Option<Value>, String> {
760 if let Some((t, target, handler)) = trap(v, "getPrototypeOf")? {
761 let reported = call(&t, &handler, vec![target.clone()])?;
762 if !with_host(|h| h.is_extensible(&target)) {
765 let actual = crate::builtins::prototype_of(&target);
766 if !with_host(|h| h.strict_eq(&reported, &actual)) {
767 return Err(invariant(
768 "'getPrototypeOf' on proxy: proxy target is non-extensible but the trap did not return its actual prototype",
769 ));
770 }
771 }
772 return Ok(Some(reported));
773 }
774 match no_trap(v, "getPrototypeOf")? {
775 Some(target) => Ok(Some(crate::builtins::prototype_of(&target))),
776 None => Ok(None),
777 }
778}
779
780pub fn set_prototype_of(v: &Value, proto: &Value) -> Result<bool, String> {
787 if let Some((t, target, handler)) = trap(v, "setPrototypeOf")? {
788 let r = call(&t, &handler, vec![target.clone(), proto.clone()])?;
789 if !with_host(|h| h.truthy(&r)) {
790 return Ok(false);
791 }
792 if !target_extensible(&target)? {
793 let actual = match get_prototype_of(&target)? {
794 Some(p) => p,
795 None => crate::builtins::prototype_of(&target),
796 };
797 if !crate::builtins::same_value(proto, &actual) {
798 return Err(invariant(
799 "'setPrototypeOf' on proxy: trap returned truish for setting a new prototype on the non-extensible proxy target",
800 ));
801 }
802 }
803 return Ok(true);
804 }
805 match no_trap(v, "setPrototypeOf")? {
806 Some(target) => {
810 if !target_extensible(&target)? {
811 let actual = match get_prototype_of(&target)? {
812 Some(p) => p,
813 None => crate::builtins::prototype_of(&target),
814 };
815 return Ok(crate::builtins::same_value(proto, &actual));
816 }
817 if crate::builtins::would_cycle_pub(&target, proto) {
818 return Ok(false);
819 }
820 with_host(|h| h.set_proto(&target, proto.clone()));
821 Ok(true)
822 }
823 None => Ok(false),
824 }
825}
826
827pub fn is_extensible(v: &Value) -> Result<Option<bool>, String> {
829 if let Some((t, target, handler)) = trap(v, "isExtensible")? {
830 let reported = call(&t, &handler, vec![target.clone()])?;
833 let reported = with_host(|h| h.truthy(&reported));
834 let actual = target_extensible(&target)?;
835 if reported != actual {
836 return Err(invariant(&format!(
837 "'isExtensible' on proxy: trap result does not reflect extensibility of proxy target (which is '{actual}')"
838 )));
839 }
840 return Ok(Some(reported));
841 }
842 match no_trap(v, "isExtensible")? {
843 Some(target) => Ok(Some(with_host(|h| h.is_extensible(&target)))),
844 None => Ok(None),
845 }
846}
847
848pub fn prevent_extensions(v: &Value) -> Result<Option<bool>, String> {
855 if let Some((t, target, handler)) = trap(v, "preventExtensions")? {
856 let r = call(&t, &handler, vec![target.clone()])?;
857 let reported = with_host(|h| h.truthy(&r));
858 if reported && target_extensible(&target)? {
859 return Err(invariant(
860 "'preventExtensions' on proxy: trap returned truish but the proxy target is extensible",
861 ));
862 }
863 return Ok(Some(reported));
864 }
865 match no_trap(v, "preventExtensions")? {
866 Some(target) => match prevent_extensions(&target)? {
867 Some(b) => Ok(Some(b)),
868 None => {
869 with_host(|h| h.prevent_extensions(&target));
870 Ok(Some(true))
871 }
872 },
873 None => Ok(None),
874 }
875}
876
877pub fn prevent_extensions_refused() -> String {
880 host::type_error("'preventExtensions' on proxy: trap returned falsish")
881}
882
883pub fn apply(v: &Value, args: Vec<Value>, this: Option<Value>) -> Result<Option<Value>, String> {
885 if let Some((t, target, handler)) = trap(v, "apply")? {
886 let this_arg = this.unwrap_or(Value::Undef);
887 let list = with_host(|h| h.new_array(args));
888 return call(&t, &handler, vec![target, this_arg, list]).map(Some);
889 }
890 match no_trap(v, "apply")? {
891 Some(target) => host::invoke(&target, args, this).map(Some),
892 None => Ok(None),
893 }
894}
895
896pub fn construct(v: &Value, args: Vec<Value>, new_target: &Value) -> Result<Option<Value>, String> {
898 if let Some((t, target, handler)) = trap(v, "construct")? {
899 let list = with_host(|h| h.new_array(args));
900 let made = call(&t, &handler, vec![target, list, new_target.clone()])?;
901 if !with_host(|h| {
903 matches!(made, Value::Obj(_)) && !h.is_null(&made) && !host::is_primitive(h, &made)
904 }) {
905 return Err(invariant(&format!(
906 "'construct' on proxy: trap returned non-object ('{}')",
907 shown(&made)
908 )));
909 }
910 return Ok(Some(made));
911 }
912 match no_trap(v, "construct")? {
913 Some(target) => {
914 let proto = if parts(new_target).is_some() {
918 Some(crate::builtins::get_property(new_target, "prototype")?)
919 } else {
920 None
921 };
922 let made = host::construct_nt(&target, args, new_target.clone())?;
923 if let Some(p) = proto {
924 let plain = matches!(p, Value::Obj(_))
925 && with_host(|h| !h.is_null(&p) && !host::is_primitive(h, &p));
926 let fresh = matches!(with_host(|h| h.get(&made).cloned()), Some(JsObj::Object(_)));
927 if plain && fresh {
928 with_host(|h| h.set_proto(&made, p));
929 }
930 }
931 Ok(Some(made))
932 }
933 None => Ok(None),
934 }
935}
936
937pub fn own_enum_string_keys(v: &Value) -> Result<Vec<String>, String> {
944 let Some(keys) = own_keys(v)? else {
945 return Ok(Vec::new());
946 };
947 let mut out = Vec::new();
948 for k in keys {
949 if host::is_symbol_key(&k) {
950 continue;
951 }
952 let Some(d) = get_own_descriptor(v, &k)? else {
953 continue;
954 };
955 let enumerable = with_host(|h| match h.get(&d) {
956 Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
957 _ => false,
958 });
959 if enumerable {
960 out.push(k);
961 }
962 }
963 Ok(out)
964}
965
966pub fn own_enumerable(v: &Value, key: &str) -> Result<bool, String> {
972 let Some(d) = get_own_descriptor(v, key)? else {
973 return Ok(false);
974 };
975 Ok(with_host(|h| match h.get(&d) {
976 Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
977 _ => false,
978 }))
979}
980
981pub fn own_enum_entries(v: &Value) -> Result<Vec<(String, Value)>, String> {
987 let Some(keys) = own_keys(v)? else {
988 return Ok(Vec::new());
989 };
990 let mut out = Vec::with_capacity(keys.len());
991 for k in keys {
992 if host::is_symbol_key(&k) || !own_enumerable(v, &k)? {
993 continue;
994 }
995 let val = get(v, &k, v)?.unwrap_or(Value::Undef);
996 out.push((k, val));
997 }
998 Ok(out)
999}
1000
1001fn wraps_array(v: &Value) -> bool {
1004 match ultimate_target(v) {
1005 Some(t) => with_host(|h| matches!(h.get(&t), Some(JsObj::Array(_)))),
1006 None => false,
1007 }
1008}
1009
1010pub fn get_iterator(v: &Value) -> Result<Option<Value>, String> {
1020 if parts(v).is_none() {
1021 return Ok(None);
1022 }
1023 let array_backed = wraps_array(v);
1024 let iter_fn = get(v, "@@iterator", v)?.unwrap_or(Value::Undef);
1025 let default_array_iter =
1032 array_backed && with_host(|h| matches!(h.get(&iter_fn), Some(JsObj::BoundMethod { .. })));
1033 if !default_array_iter && with_host(|h| host::is_callable(h, &iter_fn)) {
1034 return host::call_iterator_method(&iter_fn, v).map(Some);
1035 }
1036 if array_backed {
1037 return Ok(Some(crate::builtins::array_iterator(
1038 v,
1039 host::ArrayIterKind::Values,
1040 )));
1041 }
1042 let target = no_trap(v, "get")?.expect("checked it is a proxy");
1043 let items = host::iter_all(&target)?;
1044 Ok(Some(with_host(|h| {
1045 h.alloc(JsObj::Iter {
1046 items,
1047 idx: 0,
1048 array: None,
1049 brand: None,
1050 })
1051 })))
1052}
1053
1054pub fn iterate(v: &Value) -> Result<Option<Vec<Value>>, String> {
1057 let Some(iterator) = get_iterator(v)? else {
1058 return Ok(None);
1059 };
1060 if with_host(|h| matches!(h.get(&iterator), Some(JsObj::Iter { .. }))) {
1061 return host::iter_all(&iterator).map(Some);
1062 }
1063 host::drain_iterator(&iterator).map(Some)
1064}
1065
1066fn length_walk(v: &Value) -> Result<Vec<Value>, String> {
1070 let len_v = get(v, "length", v)?.unwrap_or(Value::Undef);
1071 let len = with_host(|h| h.to_number(&len_v));
1072 let len = if len.is_finite() && len > 0.0 {
1073 len as usize
1074 } else {
1075 0
1076 };
1077 let mut out = Vec::with_capacity(len);
1078 for i in 0..len {
1079 out.push(get(v, &i.to_string(), v)?.unwrap_or(Value::Undef));
1080 }
1081 Ok(out)
1082}
1083
1084pub fn json_snapshot(v: &Value) -> Result<Value, String> {
1088 if wraps_array(v) {
1091 let items = length_walk(v)?;
1092 return Ok(with_host(|h| h.new_array(items)));
1093 }
1094 let mut entries = Vec::new();
1097 for k in own_enum_string_keys(v)? {
1098 let val = get(v, &k, v)?.unwrap_or(Value::Undef);
1099 entries.push((k, val));
1100 }
1101 Ok(with_host(|h| {
1102 let mut m = indexmap::IndexMap::new();
1103 for (k, val) in entries {
1104 m.insert(k, val);
1105 }
1106 h.new_object(m)
1107 }))
1108}
1109
1110pub fn create(args: &[Value]) -> Result<Value, String> {
1114 let target = args.first().cloned().unwrap_or(Value::Undef);
1115 let handler = args.get(1).cloned().unwrap_or(Value::Undef);
1116 let ok = |v: &Value| {
1117 with_host(|h| matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v))
1118 };
1119 if !ok(&target) || !ok(&handler) {
1120 return Err(host::type_error(
1121 "Cannot create proxy with a non-object as target or handler",
1122 ));
1123 }
1124 Ok(with_host(|h| {
1125 h.alloc(JsObj::Proxy {
1126 target,
1127 handler,
1128 revoked: false,
1129 })
1130 }))
1131}
1132
1133pub fn revocable(args: &[Value]) -> Result<Value, String> {
1137 let proxy = create(args)?;
1138 let idx = match proxy {
1139 Value::Obj(i) => i,
1140 _ => unreachable!("create returns a heap object"),
1141 };
1142 let revoke = with_host(|h| h.alloc(JsObj::Builtin(format!("@@prevoke:{idx}"))));
1143 Ok(with_host(|h| {
1144 let mut m = indexmap::IndexMap::new();
1145 m.insert("proxy".to_string(), proxy);
1146 m.insert("revoke".to_string(), revoke);
1147 h.new_object(m)
1148 }))
1149}
1150
1151pub fn revoke(idx: u32) -> Value {
1159 with_host(|h| {
1160 if let Some(JsObj::Proxy { revoked, .. }) = h.get_mut(&Value::Obj(idx)) {
1161 *revoked = true;
1162 }
1163 });
1164 Value::Undef
1165}