use crate::host::{self, with_host, JsObj};
use fusevm::Value;
pub fn parts(v: &Value) -> Option<(Value, Value)> {
with_host(|h| match h.get(v) {
Some(JsObj::Proxy {
target, handler, ..
}) => Some((target.clone(), handler.clone())),
_ => None,
})
}
fn revoked(v: &Value) -> bool {
with_host(|h| matches!(h.get(v), Some(JsObj::Proxy { revoked, .. }) if *revoked))
}
pub fn ultimate_target(v: &Value) -> Option<Value> {
let mut cur = parts(v)?.0;
for _ in 0..100 {
match parts(&cur) {
Some((t, _)) => cur = t,
None => return Some(cur),
}
}
Some(cur)
}
pub fn is_array_subject(v: &Value) -> Result<Value, String> {
subject_through(v, "IsArray")
}
pub fn require_live(v: &Value, op: &str) -> Result<(), String> {
subject_through(v, op).map(|_| ())
}
fn subject_through(v: &Value, op: &str) -> Result<Value, String> {
let mut cur = v.clone();
while let Some((target, _)) = parts(&cur) {
if revoked(&cur) {
return Err(revoked_err(op));
}
cur = target;
}
Ok(cur)
}
fn revoked_err(op: &str) -> String {
host::type_error(&format!(
"Cannot perform '{op}' on a proxy that has been revoked"
))
}
pub fn has_trap(v: &Value, name: &str) -> bool {
matches!(trap(v, name), Ok(Some(_)))
}
fn trap(v: &Value, name: &str) -> Result<Option<(Value, Value, Value)>, String> {
let Some((target, handler)) = parts(v) else {
return Ok(None);
};
if revoked(v) {
return Err(revoked_err(name));
}
let t = crate::builtins::get_property(&handler, name)?;
if matches!(t, Value::Undef) || with_host(|h| h.is_null(&t)) {
return Ok(None);
}
if !with_host(|h| host::is_callable(h, &t)) {
return Err(host::type_error(&format!(
"'{}' returned for property '{name}' of object '#<Object>' is not a function",
with_host(|h| h.str_of(&t))
)));
}
Ok(Some((t, target, handler)))
}
fn no_trap(v: &Value, op: &str) -> Result<Option<Value>, String> {
match parts(v) {
None => Ok(None),
Some((target, _)) if !revoked(v) => Ok(Some(target)),
Some(_) => Err(revoked_err(op)),
}
}
pub fn key_value(k: &str) -> Value {
with_host(|h| {
if let Some(s) = h.symbol_of_key(k) {
return s;
}
match k.strip_prefix("@@") {
Some(name) if host::WELL_KNOWN_SYMBOLS.contains(&name) => h.well_known_symbol(name),
_ => h.new_str(k),
}
})
}
fn call(t: &Value, handler: &Value, args: Vec<Value>) -> Result<Value, String> {
host::invoke(t, args, Some(handler.clone()))
}
fn invariant(msg: &str) -> String {
host::type_error(msg)
}
fn shown(v: &Value) -> String {
crate::builtins::no_side_effects_string_pub(v)
}
#[derive(Default)]
struct Desc {
value: Option<Value>,
writable: Option<bool>,
get: Option<Value>,
set: Option<Value>,
enumerable: Option<bool>,
configurable: Option<bool>,
}
impl Desc {
fn is_accessor(&self) -> bool {
self.get.is_some() || self.set.is_some()
}
fn is_data(&self) -> bool {
self.value.is_some() || self.writable.is_some()
}
fn is_generic(&self) -> bool {
!self.is_accessor() && !self.is_data()
}
fn is_empty(&self) -> bool {
self.is_generic() && self.enumerable.is_none() && self.configurable.is_none()
}
fn from_object(obj: &Value) -> Result<Desc, String> {
if !with_host(|h| {
matches!(obj, Value::Obj(_)) && !h.is_null(obj) && !host::is_primitive(h, obj)
}) {
return Err(host::type_error(&format!(
"Property description must be an object: {}",
shown(obj)
)));
}
let field = |k: &str| -> Result<Option<Value>, String> {
if crate::builtins::has_property(obj, k)? {
crate::builtins::get_property(obj, k).map(Some)
} else {
Ok(None)
}
};
let truthy = |v: Value| with_host(|h| h.truthy(&v));
let mut d = Desc {
enumerable: field("enumerable")?.map(truthy),
configurable: field("configurable")?.map(truthy),
value: field("value")?,
writable: field("writable")?.map(truthy),
..Desc::default()
};
for (k, slot, what) in [("get", &mut d.get, "Getter"), ("set", &mut d.set, "Setter")] {
if let Some(f) = field(k)? {
if !matches!(f, Value::Undef) && !with_host(|h| host::is_callable(h, &f)) {
return Err(host::type_error(&format!(
"{what} must be a function: {}",
shown(&f)
)));
}
*slot = Some(f);
}
}
if d.is_accessor() && d.is_data() {
return Err(host::type_error(&format!(
"Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, {}",
shown(obj)
)));
}
Ok(d)
}
fn complete(mut self) -> Desc {
if self.is_generic() || self.is_data() {
self.value.get_or_insert(Value::Undef);
self.writable.get_or_insert(false);
} else {
self.get.get_or_insert(Value::Undef);
self.set.get_or_insert(Value::Undef);
}
self.enumerable.get_or_insert(false);
self.configurable.get_or_insert(false);
self
}
fn to_object(&self) -> Value {
let mut m = indexmap::IndexMap::new();
if let Some(v) = &self.value {
m.insert("value".to_string(), v.clone());
}
if let Some(w) = self.writable {
m.insert("writable".to_string(), Value::Bool(w));
}
if let Some(g) = &self.get {
m.insert("get".to_string(), g.clone());
}
if let Some(s) = &self.set {
m.insert("set".to_string(), s.clone());
}
if let Some(e) = self.enumerable {
m.insert("enumerable".to_string(), Value::Bool(e));
}
if let Some(c) = self.configurable {
m.insert("configurable".to_string(), Value::Bool(c));
}
with_host(|h| h.new_object(m))
}
}
fn target_desc(target: &Value, key: &str) -> Result<Option<Desc>, String> {
let d = crate::builtins::own_descriptor_pub(target, key_value(key))?;
if matches!(d, Value::Undef) {
return Ok(None);
}
Desc::from_object(&d).map(Some)
}
fn target_extensible(target: &Value) -> Result<bool, String> {
match is_extensible(target)? {
Some(b) => Ok(b),
None => Ok(with_host(|h| h.is_extensible(target))),
}
}
fn is_compatible(extensible: bool, desc: &Desc, current: Option<&Desc>) -> bool {
let Some(current) = current else {
return extensible;
};
if desc.is_empty() || current.configurable != Some(false) {
return true;
}
if desc.configurable == Some(true) {
return false;
}
if desc.enumerable.is_some() && desc.enumerable != current.enumerable {
return false;
}
if !desc.is_generic() && desc.is_accessor() != current.is_accessor() {
return false;
}
let differs = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
(Some(x), Some(y)) => !crate::builtins::same_value(x, y),
(Some(x), None) => !matches!(x, Value::Undef),
_ => false,
};
if current.is_accessor() {
return !differs(&desc.get, ¤t.get) && !differs(&desc.set, ¤t.set);
}
if current.writable == Some(false) {
return desc.writable != Some(true) && !differs(&desc.value, ¤t.value);
}
true
}
pub fn get(v: &Value, key: &str, receiver: &Value) -> Result<Option<Value>, String> {
if let Some((t, target, handler)) = trap(v, "get")? {
let k = key_value(key);
let got = call(&t, &handler, vec![target.clone(), k, receiver.clone()])?;
if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
if d.is_data() && d.writable == Some(false) {
let val = d.value.clone().unwrap_or(Value::Undef);
if !crate::builtins::same_value(&got, &val) {
return Err(invariant(&format!(
"'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 '{}')",
shown(&val),
shown(&got)
)));
}
}
if d.is_accessor()
&& matches!(d.get, Some(Value::Undef) | None)
&& !matches!(got, Value::Undef)
{
return Err(invariant(&format!(
"'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 '{}')",
shown(&got)
)));
}
}
return Ok(Some(got));
}
match no_trap(v, "get")? {
Some(target) => crate::builtins::get_property_recv(&target, key, receiver).map(Some),
None => Ok(None),
}
}
pub fn set(v: &Value, key: &str, val: &Value, receiver: &Value) -> Result<bool, String> {
if let Some((t, target, handler)) = trap(v, "set")? {
let k = key_value(key);
let r = call(
&t,
&handler,
vec![target.clone(), k, val.clone(), receiver.clone()],
)?;
if !with_host(|h| h.truthy(&r)) {
return Ok(false);
}
if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
if d.is_data()
&& d.writable == Some(false)
&& !crate::builtins::same_value(val, d.value.as_ref().unwrap_or(&Value::Undef))
{
return Err(invariant(&format!(
"'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"
)));
}
if d.is_accessor() && matches!(d.set, Some(Value::Undef) | None) {
return Err(invariant(&format!(
"'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"
)));
}
}
return Ok(true);
}
match no_trap(v, "set")? {
Some(target) => {
if receiver_observes_set(v, &target, key, receiver) {
return define_on_proxy_receiver(v, key, val);
}
crate::builtins::set_property_pub(&target, key, val.clone())?;
Ok(true)
}
None => Ok(false),
}
}
fn receiver_observes_set(v: &Value, target: &Value, key: &str, receiver: &Value) -> bool {
with_host(|h| h.strict_eq(receiver, v))
&& (has_trap(v, "getOwnPropertyDescriptor") || has_trap(v, "defineProperty"))
&& parts(target).is_none()
&& with_host(|h| {
host::lookup_accessor(h, target, key).is_none() && h.can_write_prop(target, key)
})
}
fn define_on_proxy_receiver(v: &Value, key: &str, val: &Value) -> Result<bool, String> {
let existing = get_own_descriptor(v, key)?.unwrap_or(Value::Undef);
let mut desc = indexmap::IndexMap::new();
desc.insert("value".to_string(), val.clone());
if !matches!(existing, Value::Undef) {
let field = |n: &str| crate::builtins::get_property(&existing, n);
let is_accessor = with_host(|h| {
host::lookup_chain(h, &existing, "get").is_some()
|| host::lookup_chain(h, &existing, "set").is_some()
});
let writable = field("writable")?;
if is_accessor || !with_host(|h| h.truthy(&writable)) {
return Ok(false);
}
} else {
for flag in ["writable", "enumerable", "configurable"] {
desc.insert(flag.to_string(), Value::Bool(true));
}
}
let desc = with_host(|h| h.new_object(desc));
if define_property(v, key, &desc)? {
return Ok(true);
}
if with_host(|h| h.current_strict()) {
return Err(host::type_error(&format!(
"'defineProperty' on proxy: trap returned falsish for property '{key}'"
)));
}
Ok(false)
}
pub fn has(v: &Value, key: &str) -> Result<Option<bool>, String> {
if let Some((t, target, handler)) = trap(v, "has")? {
let k = key_value(key);
let r = call(&t, &handler, vec![target.clone(), k])?;
let reported = with_host(|h| h.truthy(&r));
if !reported {
if let Some(d) = target_desc(&target, key)? {
if d.configurable == Some(false) {
return Err(invariant(&format!(
"'has' on proxy: trap returned falsish for property '{key}' which exists in the proxy target as non-configurable"
)));
}
if !target_extensible(&target)? {
return Err(invariant(&format!(
"'has' on proxy: trap returned falsish for property '{key}' but the proxy target is not extensible"
)));
}
}
}
return Ok(Some(reported));
}
match no_trap(v, "has")? {
Some(target) => crate::builtins::has_property(&target, key).map(Some),
None => Ok(None),
}
}
pub fn delete(v: &Value, key: &str) -> Result<Option<bool>, String> {
if let Some((t, target, handler)) = trap(v, "deleteProperty")? {
let k = key_value(key);
let r = call(&t, &handler, vec![target.clone(), k])?;
let reported = with_host(|h| h.truthy(&r));
if reported {
if let Some(d) = target_desc(&target, key)? {
if d.configurable == Some(false) {
return Err(invariant(&format!(
"'deleteProperty' on proxy: trap returned truish for property '{key}' which is non-configurable in the proxy target"
)));
}
if !target_extensible(&target)? {
return Err(invariant(&format!(
"'deleteProperty' on proxy: trap returned truish for property '{key}' but the proxy target is non-extensible"
)));
}
}
}
return Ok(Some(reported));
}
match no_trap(v, "deleteProperty")? {
Some(target) => crate::builtins::delete_property(&target, key).map(Some),
None => Ok(None),
}
}
pub fn own_keys(v: &Value) -> Result<Option<Vec<String>>, String> {
if let Some((t, target, handler)) = trap(v, "ownKeys")? {
let r = call(&t, &handler, vec![target.clone()])?;
if !with_host(|h| {
matches!(r, Value::Obj(_)) && !h.is_null(&r) && !host::is_primitive(h, &r)
}) {
return Err(host::type_error(
"CreateListFromArrayLike called on non-object",
));
}
let len = crate::builtins::length_of_array_like(&r)?;
let mut out = Vec::with_capacity(len);
for i in 0..len {
let k = crate::builtins::get_property(&r, &i.to_string())?;
let is_key = with_host(|h| {
h.as_str(&k).is_some() || matches!(h.get(&k), Some(JsObj::Symbol { .. }))
});
if !is_key {
return Err(host::type_error(&format!(
"{} is not a valid property name",
shown(&k)
)));
}
out.push(host::to_property_key(&k)?);
}
let mut seen: Vec<&String> = Vec::with_capacity(out.len());
for k in &out {
if seen.contains(&k) {
return Err(invariant(
"'ownKeys' on proxy: trap returned duplicate entries",
));
}
seen.push(k);
}
let target_keys = with_host(|h| {
let mut ks = h.own_key_names(&target, false);
ks.extend(
h.own_symbol_keys(&target)
.iter()
.map(|sym| h.property_key(sym))
.collect::<Vec<_>>(),
);
ks
});
for k in &target_keys {
let pinned =
crate::builtins::own_prop_facts(&target, k).is_some_and(|(_, _, conf, _)| !conf);
if pinned && !out.contains(k) {
return Err(invariant(&format!(
"'ownKeys' on proxy: trap result did not include '{k}'"
)));
}
}
if !with_host(|h| h.is_extensible(&target)) {
for k in &target_keys {
if !out.contains(k) {
return Err(invariant(&format!(
"'ownKeys' on proxy: trap result did not include '{k}'"
)));
}
}
for k in &out {
if !target_keys.contains(k) {
return Err(invariant(
"'ownKeys' on proxy: trap returned extra keys but proxy target is non-extensible",
));
}
}
}
return Ok(Some(out));
}
match no_trap(v, "ownKeys")? {
Some(target) => {
let mut keys = with_host(|h| h.own_key_names(&target, false));
keys.extend(with_host(|h| {
h.own_symbol_keys(&target)
.iter()
.map(|s| h.property_key(s))
.collect::<Vec<_>>()
}));
Ok(Some(keys))
}
None => Ok(None),
}
}
pub fn get_own_descriptor(v: &Value, key: &str) -> Result<Option<Value>, String> {
if let Some((t, target, handler)) = trap(v, "getOwnPropertyDescriptor")? {
let k = key_value(key);
let d = call(&t, &handler, vec![target.clone(), k])?;
return checked_own_descriptor(&target, key, &d).map(Some);
}
match no_trap(v, "getOwnPropertyDescriptor")? {
Some(target) => {
let k = key_value(key);
crate::builtins::own_descriptor_pub(&target, k).map(Some)
}
None => Ok(None),
}
}
fn checked_own_descriptor(target: &Value, key: &str, d: &Value) -> Result<Value, String> {
let is_object =
with_host(|h| matches!(d, Value::Obj(_)) && !h.is_null(d) && !host::is_primitive(h, d));
if !is_object && !matches!(d, Value::Undef) {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap returned neither object nor undefined for property '{key}'"
)));
}
let target_d = target_desc(target, key)?;
if !is_object {
if let Some(td) = &target_d {
if td.configurable == Some(false) {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which is non-configurable in the proxy target"
)));
}
if !target_extensible(target)? {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which exists in the non-extensible proxy target"
)));
}
}
return Ok(Value::Undef);
}
let extensible = target_extensible(target)?;
let result = Desc::from_object(d)?.complete();
if !is_compatible(extensible, &result, target_d.as_ref()) {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap returned descriptor for property '{key}' that is incompatible with the existing property in the proxy target"
)));
}
if result.configurable == Some(false) {
match &target_d {
Some(td) if td.configurable == Some(false) => {
if result.writable == Some(false) && td.writable == Some(true) {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap reported non-configurable and non-writable for property '{key}' which is non-configurable, writable in the proxy target"
)));
}
}
_ => {
return Err(invariant(&format!(
"'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for property '{key}' which is either non-existent or configurable in the proxy target"
)));
}
}
}
Ok(result.to_object())
}
pub fn define_property(v: &Value, key: &str, desc: &Value) -> Result<bool, String> {
if let Some((t, target, handler)) = trap(v, "defineProperty")? {
let k = key_value(key);
let d = Desc::from_object(desc)?;
let r = call(&t, &handler, vec![target.clone(), k, d.to_object()])?;
if !with_host(|h| h.truthy(&r)) {
return Ok(false);
}
let target_d = target_desc(&target, key)?;
let extensible = target_extensible(&target)?;
let setting_config_false = d.configurable == Some(false);
let non_configurable = || {
invariant(&format!(
"'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which is either non-existent or configurable in the proxy target"
))
};
match &target_d {
None => {
if !extensible {
return Err(invariant(&format!(
"'defineProperty' on proxy: trap returned truish for adding property '{key}' to the non-extensible proxy target"
)));
}
if setting_config_false {
return Err(non_configurable());
}
}
Some(td) => {
if !is_compatible(extensible, &d, Some(td)) {
return Err(invariant(&format!(
"'defineProperty' on proxy: trap returned truish for adding property '{key}' that is incompatible with the existing property in the proxy target"
)));
}
if setting_config_false && td.configurable == Some(true) {
return Err(non_configurable());
}
if td.is_data()
&& td.configurable == Some(false)
&& td.writable == Some(true)
&& d.writable == Some(false)
{
return Err(invariant(&format!(
"'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."
)));
}
}
}
return Ok(true);
}
match no_trap(v, "defineProperty")? {
Some(target) => {
let k = key_value(key);
crate::builtins::define_property_pub(&target, k, desc.clone())?;
Ok(true)
}
None => Ok(false),
}
}
pub fn get_prototype_of(v: &Value) -> Result<Option<Value>, String> {
if let Some((t, target, handler)) = trap(v, "getPrototypeOf")? {
let reported = call(&t, &handler, vec![target.clone()])?;
if !with_host(|h| h.is_extensible(&target)) {
let actual = crate::builtins::prototype_of(&target);
if !with_host(|h| h.strict_eq(&reported, &actual)) {
return Err(invariant(
"'getPrototypeOf' on proxy: proxy target is non-extensible but the trap did not return its actual prototype",
));
}
}
return Ok(Some(reported));
}
match no_trap(v, "getPrototypeOf")? {
Some(target) => Ok(Some(crate::builtins::prototype_of(&target))),
None => Ok(None),
}
}
pub fn set_prototype_of(v: &Value, proto: &Value) -> Result<bool, String> {
if let Some((t, target, handler)) = trap(v, "setPrototypeOf")? {
let r = call(&t, &handler, vec![target.clone(), proto.clone()])?;
if !with_host(|h| h.truthy(&r)) {
return Ok(false);
}
if !target_extensible(&target)? {
let actual = match get_prototype_of(&target)? {
Some(p) => p,
None => crate::builtins::prototype_of(&target),
};
if !crate::builtins::same_value(proto, &actual) {
return Err(invariant(
"'setPrototypeOf' on proxy: trap returned truish for setting a new prototype on the non-extensible proxy target",
));
}
}
return Ok(true);
}
match no_trap(v, "setPrototypeOf")? {
Some(target) => {
if !target_extensible(&target)? {
let actual = match get_prototype_of(&target)? {
Some(p) => p,
None => crate::builtins::prototype_of(&target),
};
return Ok(crate::builtins::same_value(proto, &actual));
}
if crate::builtins::would_cycle_pub(&target, proto) {
return Ok(false);
}
with_host(|h| h.set_proto(&target, proto.clone()));
Ok(true)
}
None => Ok(false),
}
}
pub fn is_extensible(v: &Value) -> Result<Option<bool>, String> {
if let Some((t, target, handler)) = trap(v, "isExtensible")? {
let reported = call(&t, &handler, vec![target.clone()])?;
let reported = with_host(|h| h.truthy(&reported));
let actual = target_extensible(&target)?;
if reported != actual {
return Err(invariant(&format!(
"'isExtensible' on proxy: trap result does not reflect extensibility of proxy target (which is '{actual}')"
)));
}
return Ok(Some(reported));
}
match no_trap(v, "isExtensible")? {
Some(target) => Ok(Some(with_host(|h| h.is_extensible(&target)))),
None => Ok(None),
}
}
pub fn prevent_extensions(v: &Value) -> Result<Option<bool>, String> {
if let Some((t, target, handler)) = trap(v, "preventExtensions")? {
let r = call(&t, &handler, vec![target.clone()])?;
let reported = with_host(|h| h.truthy(&r));
if reported && target_extensible(&target)? {
return Err(invariant(
"'preventExtensions' on proxy: trap returned truish but the proxy target is extensible",
));
}
return Ok(Some(reported));
}
match no_trap(v, "preventExtensions")? {
Some(target) => match prevent_extensions(&target)? {
Some(b) => Ok(Some(b)),
None => {
with_host(|h| h.prevent_extensions(&target));
Ok(Some(true))
}
},
None => Ok(None),
}
}
pub fn prevent_extensions_refused() -> String {
host::type_error("'preventExtensions' on proxy: trap returned falsish")
}
pub fn apply(v: &Value, args: Vec<Value>, this: Option<Value>) -> Result<Option<Value>, String> {
if let Some((t, target, handler)) = trap(v, "apply")? {
let this_arg = this.unwrap_or(Value::Undef);
let list = with_host(|h| h.new_array(args));
return call(&t, &handler, vec![target, this_arg, list]).map(Some);
}
match no_trap(v, "apply")? {
Some(target) => host::invoke(&target, args, this).map(Some),
None => Ok(None),
}
}
pub fn construct(v: &Value, args: Vec<Value>, new_target: &Value) -> Result<Option<Value>, String> {
if let Some((t, target, handler)) = trap(v, "construct")? {
let list = with_host(|h| h.new_array(args));
let made = call(&t, &handler, vec![target, list, new_target.clone()])?;
if !with_host(|h| {
matches!(made, Value::Obj(_)) && !h.is_null(&made) && !host::is_primitive(h, &made)
}) {
return Err(invariant(&format!(
"'construct' on proxy: trap returned non-object ('{}')",
shown(&made)
)));
}
return Ok(Some(made));
}
match no_trap(v, "construct")? {
Some(target) => {
let proto = if parts(new_target).is_some() {
Some(crate::builtins::get_property(new_target, "prototype")?)
} else {
None
};
let made = host::construct_nt(&target, args, new_target.clone())?;
if let Some(p) = proto {
let plain = matches!(p, Value::Obj(_))
&& with_host(|h| !h.is_null(&p) && !host::is_primitive(h, &p));
let fresh = matches!(with_host(|h| h.get(&made).cloned()), Some(JsObj::Object(_)));
if plain && fresh {
with_host(|h| h.set_proto(&made, p));
}
}
Ok(Some(made))
}
None => Ok(None),
}
}
pub fn own_enum_string_keys(v: &Value) -> Result<Vec<String>, String> {
let Some(keys) = own_keys(v)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for k in keys {
if host::is_symbol_key(&k) {
continue;
}
let Some(d) = get_own_descriptor(v, &k)? else {
continue;
};
let enumerable = with_host(|h| match h.get(&d) {
Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
_ => false,
});
if enumerable {
out.push(k);
}
}
Ok(out)
}
pub fn own_enumerable(v: &Value, key: &str) -> Result<bool, String> {
let Some(d) = get_own_descriptor(v, key)? else {
return Ok(false);
};
Ok(with_host(|h| match h.get(&d) {
Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
_ => false,
}))
}
pub fn own_enum_entries(v: &Value) -> Result<Vec<(String, Value)>, String> {
let Some(keys) = own_keys(v)? else {
return Ok(Vec::new());
};
let mut out = Vec::with_capacity(keys.len());
for k in keys {
if host::is_symbol_key(&k) || !own_enumerable(v, &k)? {
continue;
}
let val = get(v, &k, v)?.unwrap_or(Value::Undef);
out.push((k, val));
}
Ok(out)
}
fn wraps_array(v: &Value) -> bool {
match ultimate_target(v) {
Some(t) => with_host(|h| matches!(h.get(&t), Some(JsObj::Array(_)))),
None => false,
}
}
pub fn get_iterator(v: &Value) -> Result<Option<Value>, String> {
if parts(v).is_none() {
return Ok(None);
}
let array_backed = wraps_array(v);
let iter_fn = get(v, "@@iterator", v)?.unwrap_or(Value::Undef);
let default_array_iter =
array_backed && with_host(|h| matches!(h.get(&iter_fn), Some(JsObj::BoundMethod { .. })));
if !default_array_iter && with_host(|h| host::is_callable(h, &iter_fn)) {
return host::call_iterator_method(&iter_fn, v).map(Some);
}
if array_backed {
return Ok(Some(crate::builtins::array_iterator(
v,
host::ArrayIterKind::Values,
)));
}
let target = no_trap(v, "get")?.expect("checked it is a proxy");
let items = host::iter_all(&target)?;
Ok(Some(with_host(|h| {
h.alloc(JsObj::Iter {
items,
idx: 0,
array: None,
brand: None,
})
})))
}
pub fn iterate(v: &Value) -> Result<Option<Vec<Value>>, String> {
let Some(iterator) = get_iterator(v)? else {
return Ok(None);
};
if with_host(|h| matches!(h.get(&iterator), Some(JsObj::Iter { .. }))) {
return host::iter_all(&iterator).map(Some);
}
host::drain_iterator(&iterator).map(Some)
}
fn length_walk(v: &Value) -> Result<Vec<Value>, String> {
let len_v = get(v, "length", v)?.unwrap_or(Value::Undef);
let len = with_host(|h| h.to_number(&len_v));
let len = if len.is_finite() && len > 0.0 {
len as usize
} else {
0
};
let mut out = Vec::with_capacity(len);
for i in 0..len {
out.push(get(v, &i.to_string(), v)?.unwrap_or(Value::Undef));
}
Ok(out)
}
pub fn json_snapshot(v: &Value) -> Result<Value, String> {
if wraps_array(v) {
let items = length_walk(v)?;
return Ok(with_host(|h| h.new_array(items)));
}
let mut entries = Vec::new();
for k in own_enum_string_keys(v)? {
let val = get(v, &k, v)?.unwrap_or(Value::Undef);
entries.push((k, val));
}
Ok(with_host(|h| {
let mut m = indexmap::IndexMap::new();
for (k, val) in entries {
m.insert(k, val);
}
h.new_object(m)
}))
}
pub fn create(args: &[Value]) -> Result<Value, String> {
let target = args.first().cloned().unwrap_or(Value::Undef);
let handler = args.get(1).cloned().unwrap_or(Value::Undef);
let ok = |v: &Value| {
with_host(|h| matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v))
};
if !ok(&target) || !ok(&handler) {
return Err(host::type_error(
"Cannot create proxy with a non-object as target or handler",
));
}
Ok(with_host(|h| {
h.alloc(JsObj::Proxy {
target,
handler,
revoked: false,
})
}))
}
pub fn revocable(args: &[Value]) -> Result<Value, String> {
let proxy = create(args)?;
let idx = match proxy {
Value::Obj(i) => i,
_ => unreachable!("create returns a heap object"),
};
let revoke = with_host(|h| h.alloc(JsObj::Builtin(format!("@@prevoke:{idx}"))));
Ok(with_host(|h| {
let mut m = indexmap::IndexMap::new();
m.insert("proxy".to_string(), proxy);
m.insert("revoke".to_string(), revoke);
h.new_object(m)
}))
}
pub fn revoke(idx: u32) -> Value {
with_host(|h| {
if let Some(JsObj::Proxy { revoked, .. }) = h.get_mut(&Value::Obj(idx)) {
*revoked = true;
}
});
Value::Undef
}