use std::cell::RefCell;
use js_compile::bytecode::Function as CompiledFunction;
use js_gc::{Gc, Trace, Tracer, WeakGc};
use std::fmt;
use std::rc::Rc;
use crate::value::{Cell, JsSymbol, Value};
pub struct BufferStorage {
pub bytes: Vec<u8>,
pub detached: bool,
}
impl JsObject {
pub fn array_buffer_storage(&self) -> Option<Rc<RefCell<BufferStorage>>> {
match &self.data.borrow().kind {
ObjectKind::ArrayBuffer(storage) => Some(storage.clone()),
_ => None,
}
}
pub fn set_array_buffer(&self, storage: Rc<RefCell<BufferStorage>>) {
self.data.borrow_mut().kind = ObjectKind::ArrayBuffer(storage);
}
pub fn collection_entries(&self) -> Option<Vec<(Value, Value)>> {
match &self.data.borrow().kind {
ObjectKind::Collection { entries, .. } => Some(entries.clone()),
_ => None,
}
}
pub fn collection_is_set(&self) -> Option<bool> {
match &self.data.borrow().kind {
ObjectKind::Collection { is_set, .. } => Some(*is_set),
_ => None,
}
}
pub fn set_collection(&self, entries: Vec<(Value, Value)>, is_set: bool) {
self.data.borrow_mut().kind = ObjectKind::Collection { entries, is_set };
}
pub fn weak_entries(&self) -> Option<Vec<(Value, Value)>> {
match &self.data.borrow().kind {
ObjectKind::WeakCollection { entries, .. } => Some(
entries
.iter()
.filter_map(|(key, value)| key.upgrade().map(|key| (key, value.clone())))
.collect(),
),
_ => None,
}
}
pub fn weak_is_set(&self) -> Option<bool> {
match &self.data.borrow().kind {
ObjectKind::WeakCollection { is_set, .. } => Some(*is_set),
_ => None,
}
}
pub fn set_weak_collection(&self, entries: Vec<(WeakKey, Value)>, is_set: bool) {
self.data.borrow_mut().kind = ObjectKind::WeakCollection { entries, is_set };
}
pub fn weak_set(&self, key: WeakKey, value: Value) {
let mut data = self.data.borrow_mut();
let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
return;
};
entries.retain(|(existing, _)| !existing.is_expired());
for (existing, slot) in entries.iter_mut() {
if existing.same(&key) {
*slot = value;
return;
}
}
entries.push((key, value));
}
pub fn weak_delete(&self, key: &Value) -> bool {
let mut data = self.data.borrow_mut();
let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
return false;
};
let before = entries.len();
entries.retain(|(existing, _)| !existing.is_expired() && !existing.matches(key));
entries.len() != before
}
pub fn weak_ref_target(&self) -> Option<WeakKey> {
match &self.data.borrow().kind {
ObjectKind::WeakRef { target } => Some(target.clone()),
_ => None,
}
}
pub fn set_weak_ref(&self, target: WeakKey) {
self.data.borrow_mut().kind = ObjectKind::WeakRef { target };
}
pub fn finalization_state(&self) -> Option<Box<FinalizationState>> {
match &self.data.borrow().kind {
ObjectKind::Finalization(state) => Some(Box::new(FinalizationState {
registrations: state
.registrations
.iter()
.map(|registration| Registration {
target: registration.target.clone(),
held_value: registration.held_value.clone(),
token: registration.token.clone(),
})
.collect(),
cleanup: state.cleanup.clone(),
})),
_ => None,
}
}
pub fn set_finalization_state(&self, state: FinalizationState) {
self.data.borrow_mut().kind = ObjectKind::Finalization(Box::new(state));
}
pub fn typed_array_parts(
&self,
) -> Option<(
Gc<JsObject>,
crate::builtins::typedarray::ElementType,
usize,
usize,
)> {
match &self.data.borrow().kind {
ObjectKind::TypedArray {
buffer,
element,
offset,
length,
} => Some((buffer.clone(), *element, *offset, *length)),
_ => None,
}
}
pub fn is_native_function(&self) -> bool {
matches!(
&self.data.borrow().kind,
ObjectKind::Function(Callable::Native { .. })
)
}
pub fn native_creates_own_instance(&self) -> bool {
matches!(
&self.data.borrow().kind,
ObjectKind::Function(Callable::Native {
own_instance: true,
..
})
)
}
pub fn set_data_view(&self, buffer: Gc<JsObject>, offset: usize, length: usize) {
self.data.borrow_mut().kind = ObjectKind::DataView {
buffer,
offset,
length,
};
}
pub fn data_view_parts(&self) -> Option<(Gc<JsObject>, usize, usize)> {
match &self.data.borrow().kind {
ObjectKind::DataView {
buffer,
offset,
length,
} => Some((buffer.clone(), *offset, *length)),
_ => None,
}
}
pub fn set_typed_array(
&self,
buffer: Gc<JsObject>,
element: crate::builtins::typedarray::ElementType,
offset: usize,
length: usize,
) {
self.data.borrow_mut().kind = ObjectKind::TypedArray {
buffer,
element,
offset,
length,
};
}
pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
self.typed_array_parts().map(|(_, element, _, _)| element)
}
pub fn typed_array_length(&self) -> Option<usize> {
let (buffer, _, _, length) = self.typed_array_parts()?;
let storage = buffer.array_buffer_storage()?;
if storage.borrow().detached {
return Some(0);
}
Some(length)
}
pub fn typed_array_element(&self, index: usize) -> Option<Value> {
let (buffer, element, offset, length) = self.typed_array_parts()?;
let storage = buffer.array_buffer_storage()?;
let storage = storage.borrow();
if storage.detached || index >= length {
return Some(Value::Undefined);
}
Some(element.read(
buffer.heap(),
&storage.bytes,
offset + index * element.size(),
))
}
pub fn typed_array_set(&self, index: usize, value: Value) -> Option<Result<(), &'static str>> {
let (buffer, element, offset, length) = self.typed_array_parts()?;
if index >= length {
return Some(Ok(()));
}
let storage = buffer.array_buffer_storage()?;
let mut storage = storage.borrow_mut();
if storage.detached {
return Some(Ok(()));
}
let stored = element.write(&mut storage.bytes, offset + index * element.size(), &value);
Some(stored)
}
}
#[derive(Clone, Default)]
pub struct Property {
pub value: Option<Value>,
pub getter: Option<Value>,
pub setter: Option<Value>,
pub writable: bool,
pub enumerable: bool,
pub configurable: bool,
}
impl Property {
pub fn data(value: Value) -> Property {
Property {
value: Some(value),
writable: true,
enumerable: true,
configurable: true,
..Property::default()
}
}
pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
Property {
value: Some(value),
writable,
enumerable,
configurable: writable,
..Property::default()
}
}
pub fn name_or_length(value: Value) -> Property {
Property {
value: Some(value),
writable: false,
enumerable: false,
configurable: true,
..Property::default()
}
}
pub fn prototype_of(value: Value, writable: bool) -> Property {
Property {
value: Some(value),
writable,
enumerable: false,
configurable: false,
..Property::default()
}
}
pub fn accessor_with(
getter: Option<Value>,
setter: Option<Value>,
enumerable: bool,
) -> Property {
Property {
getter,
setter,
enumerable,
configurable: true,
..Property::default()
}
}
pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
Property {
getter,
setter,
enumerable: true,
configurable: true,
..Property::default()
}
}
pub fn is_accessor(&self) -> bool {
self.getter.is_some() || self.setter.is_some()
}
}
impl Trace for Property {
fn trace(&self, tracer: &mut Tracer) {
self.value.trace(tracer);
self.getter.trace(tracer);
self.setter.trace(tracer);
}
}
pub type NativeFn =
fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
pub enum Callable {
Bytecode {
code: Gc<CompiledCode>,
env: Gc<ClosureEnv>,
},
Bound {
target: Value,
this: Value,
args: Vec<Value>,
},
Native {
func: NativeFn,
own_instance: bool,
},
Revoker(crate::object::ProxyRef),
PromiseResolve(Gc<JsObject>),
PromiseReject(Gc<JsObject>),
AwaitResume {
coroutine: Gc<JsObject>,
promise: Gc<JsObject>,
kind: crate::interp::ResumeKind,
},
CombinatorSettle {
state: Gc<JsObject>,
index: usize,
fulfilled: bool,
},
SettlePromise {
promise: Gc<JsObject>,
value: Value,
rejected: bool,
},
GeneratorResume {
generator: Gc<JsObject>,
promise: Gc<JsObject>,
kind: crate::interp::ResumeKind,
},
ModuleBinding {
cell: Gc<Cell>,
},
YieldResult {
promise: Gc<JsObject>,
done: bool,
},
DisposeStep {
remaining: Gc<JsObject>,
promise: Gc<JsObject>,
error: Value,
rejected: bool,
},
FinallyShim {
callback: Option<Value>,
fulfilled: bool,
},
}
impl Trace for Callable {
fn trace(&self, tracer: &mut Tracer) {
match self {
Callable::Bytecode { code, env } => {
tracer.visit(code);
tracer.visit(env);
}
Callable::Bound { target, this, args } => {
target.trace(tracer);
this.trace(tracer);
for argument in args {
argument.trace(tracer);
}
}
Callable::Native { .. } => {}
Callable::Revoker(slots) => slots.borrow().trace(tracer),
Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
tracer.visit(promise)
}
Callable::AwaitResume {
coroutine, promise, ..
} => {
tracer.visit(coroutine);
tracer.visit(promise);
}
Callable::CombinatorSettle { state, .. } => tracer.visit(state),
Callable::GeneratorResume {
generator, promise, ..
} => {
tracer.visit(generator);
tracer.visit(promise);
}
Callable::YieldResult { promise, .. } => tracer.visit(promise),
Callable::ModuleBinding { cell } => tracer.visit(cell),
Callable::DisposeStep {
remaining,
promise,
error,
..
} => {
tracer.visit(remaining);
tracer.visit(promise);
error.trace(tracer);
}
Callable::SettlePromise { promise, value, .. } => {
tracer.visit(promise);
value.trace(tracer);
}
Callable::FinallyShim { callback, .. } => {
if let Some(callback) = callback {
callback.trace(tracer);
}
}
}
}
}
pub struct CompiledCode {
pub code: CompiledFunction,
pub arg_cell: Vec<i32>,
pub loc_cell: Vec<i32>,
}
impl CompiledCode {
pub fn new(code: CompiledFunction) -> CompiledCode {
let mut next = 0i32;
let mut arg_cell = vec![-1; code.args.len()];
for (slot, arg) in code.args.iter().enumerate() {
if arg.is_captured {
arg_cell[slot] = next;
next += 1;
}
}
let mut loc_cell = vec![-1; code.vars.len()];
for (slot, local) in code.vars.iter().enumerate() {
if local.is_captured {
loc_cell[slot] = next;
next += 1;
}
}
CompiledCode {
code,
arg_cell,
loc_cell,
}
}
}
impl Trace for CompiledCode {
fn trace(&self, _tracer: &mut Tracer) {}
}
pub struct ClosureEnv {
pub cells: Vec<Gc<Cell>>,
pub eval_scope: Option<Gc<EvalScope>>,
pub local_vars: Option<Gc<LocalVars>>,
pub local_phase: u8,
}
pub struct LocalVars {
names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
}
impl Default for LocalVars {
fn default() -> LocalVars {
LocalVars::new()
}
}
impl LocalVars {
pub fn new() -> LocalVars {
LocalVars {
names: std::cell::RefCell::new(Vec::new()),
}
}
pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
self.names
.borrow()
.iter()
.find(|(bound, _, at)| bound == name && *at <= phase)
.map(|(_, cell, _)| cell.clone())
}
pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
let mut names = self.names.borrow_mut();
if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
return cell.clone();
}
names.push((name.to_string(), cell.clone(), phase));
cell
}
pub fn contains(&self, name: &str) -> bool {
self.names
.borrow()
.iter()
.any(|(bound, _, _)| bound == name)
}
}
impl Trace for LocalVars {
fn trace(&self, tracer: &mut Tracer) {
for (_, cell, _) in self.names.borrow().iter() {
tracer.visit(cell);
}
}
}
impl Trace for ClosureEnv {
fn trace(&self, tracer: &mut Tracer) {
for cell in &self.cells {
tracer.visit(cell);
}
if let Some(scope) = &self.eval_scope {
tracer.visit(scope);
}
if let Some(local_vars) = &self.local_vars {
tracer.visit(local_vars);
}
}
}
pub struct EvalScope {
pub names: Vec<(String, Gc<Cell>)>,
}
impl EvalScope {
pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
self.names
.iter()
.find(|(bound, _)| bound == name)
.map(|(_, cell)| cell)
}
}
impl Trace for EvalScope {
fn trace(&self, tracer: &mut Tracer) {
for (_, cell) in &self.names {
tracer.visit(cell);
}
}
}
pub enum ObjectKind {
Ordinary,
Array {
elements: Vec<Value>,
length: usize,
},
Function(Callable),
RegExp(crate::builtins::regexp::RegExpData),
DisposableStack(crate::builtins::disposable::StackState),
ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
Collection {
entries: Vec<(Value, Value)>,
is_set: bool,
},
DataView {
buffer: Gc<JsObject>,
offset: usize,
length: usize,
},
TypedArray {
buffer: Gc<JsObject>,
element: crate::builtins::typedarray::ElementType,
offset: usize,
length: usize,
},
Generator(Box<crate::interp::GeneratorState>),
Proxy(ProxyRef),
Promise(PromiseRef),
WeakCollection {
entries: Vec<(WeakKey, Value)>,
is_set: bool,
},
WeakRef {
target: WeakKey,
},
Finalization(Box<FinalizationState>),
}
pub struct FinalizationState {
pub registrations: Vec<Registration>,
pub cleanup: Value,
}
#[derive(Clone)]
pub enum WeakKey {
Object(WeakGc<JsObject>),
Symbol(WeakGc<JsSymbol>),
}
impl WeakKey {
pub fn is_expired(&self) -> bool {
match self {
WeakKey::Object(handle) => handle.is_expired(),
WeakKey::Symbol(handle) => handle.is_expired(),
}
}
pub fn same(&self, other: &WeakKey) -> bool {
match (self, other) {
(WeakKey::Object(left), WeakKey::Object(right)) => left.ptr_eq(right),
(WeakKey::Symbol(left), WeakKey::Symbol(right)) => left.ptr_eq(right),
_ => false,
}
}
pub fn matches(&self, value: &Value) -> bool {
match (self, value) {
(WeakKey::Object(handle), Value::Object(object)) => object.upgrades_to(handle),
(WeakKey::Symbol(handle), Value::Symbol(symbol)) => symbol.upgrades_to(handle),
_ => false,
}
}
pub fn upgrade(&self) -> Option<Value> {
match self {
WeakKey::Object(handle) => handle.upgrade().map(Value::Object),
WeakKey::Symbol(handle) => handle.upgrade().map(Value::Symbol),
}
}
}
impl Trace for WeakKey {
fn trace(&self, _tracer: &mut Tracer) {}
}
pub fn weak_key(value: &Value) -> Option<WeakKey> {
match value {
Value::Object(object) => Some(WeakKey::Object(object.downgrade())),
Value::Symbol(symbol) if symbol.registry_key().is_none() => {
Some(WeakKey::Symbol(symbol.downgrade()))
}
_ => None,
}
}
pub struct Registration {
pub target: WeakKey,
pub held_value: Value,
pub token: Option<Value>,
}
#[derive(Default)]
pub struct ProxyState {
pub target: Option<Gc<JsObject>>,
pub handler: Option<Value>,
pub callable: bool,
pub constructible: bool,
}
pub struct PromiseState {
pub status: PromiseStatus,
pub reactions: Vec<PromiseReaction>,
pub handled: bool,
}
impl Default for PromiseState {
fn default() -> Self {
PromiseState {
status: PromiseStatus::Pending,
reactions: Vec::new(),
handled: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CombinatorKind {
All,
AllSettled,
Any,
Race,
}
#[derive(Clone, Default)]
pub enum PromiseStatus {
#[default]
Pending,
Fulfilled(Value),
Rejected(Value),
}
#[derive(Clone)]
pub struct PromiseReaction {
pub on_fulfilled: Option<Value>,
pub on_rejected: Option<Value>,
pub promise: Gc<JsObject>,
}
impl Trace for PromiseState {
fn trace(&self, tracer: &mut Tracer) {
match &self.status {
PromiseStatus::Pending => {}
PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
}
for reaction in &self.reactions {
if let Some(on_fulfilled) = &reaction.on_fulfilled {
on_fulfilled.trace(tracer);
}
if let Some(on_rejected) = &reaction.on_rejected {
on_rejected.trace(tracer);
}
tracer.visit(&reaction.promise);
}
}
}
pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
impl Trace for ProxyState {
fn trace(&self, tracer: &mut Tracer) {
if let Some(target) = &self.target {
tracer.visit(target);
}
if let Some(handler) = &self.handler {
handler.trace(tracer);
}
}
}
impl Trace for ObjectKind {
fn trace(&self, tracer: &mut Tracer) {
match self {
ObjectKind::RegExp(_) => {}
ObjectKind::DisposableStack(state) => state.trace(tracer),
ObjectKind::ArrayBuffer(_) => {}
ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
tracer.visit(buffer)
}
ObjectKind::Collection { entries, .. } => {
for (key, value) in entries {
key.trace(tracer);
value.trace(tracer);
}
}
ObjectKind::Ordinary => {}
ObjectKind::Array { elements, .. } => {
for element in elements {
element.trace(tracer);
}
}
ObjectKind::Function(callable) => callable.trace(tracer),
ObjectKind::Generator(state) => state.trace(tracer),
ObjectKind::Proxy(state) => state.borrow().trace(tracer),
ObjectKind::Promise(state) => state.borrow().trace(tracer),
ObjectKind::WeakCollection { entries, .. } => {
for (_, value) in entries {
value.trace(tracer);
}
}
ObjectKind::WeakRef { .. } => {}
ObjectKind::Finalization(state) => {
state.cleanup.trace(tracer);
for registration in &state.registrations {
registration.held_value.trace(tracer);
registration.token.trace(tracer);
}
}
}
}
}
#[derive(Clone)]
pub enum PropertyKey {
String(crate::value::Wtf8),
Symbol(Gc<JsSymbol>),
}
impl PropertyKey {
pub fn as_str(&self) -> Option<&str> {
match self {
PropertyKey::String(text) => text.as_str(),
PropertyKey::Symbol(_) => None,
}
}
pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
match self {
PropertyKey::String(text) => Some(text),
PropertyKey::Symbol(_) => None,
}
}
pub fn is_symbol(&self) -> bool {
matches!(self, PropertyKey::Symbol(_))
}
}
impl fmt::Display for PropertyKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
}
}
}
impl PartialEq for PropertyKey {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(PropertyKey::String(a), PropertyKey::String(b)) => a == b,
(PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
_ => false,
}
}
}
impl From<&str> for PropertyKey {
fn from(text: &str) -> PropertyKey {
PropertyKey::String(crate::value::Wtf8::new(text))
}
}
impl From<String> for PropertyKey {
fn from(text: String) -> PropertyKey {
PropertyKey::String(crate::value::Wtf8::new(text))
}
}
impl From<crate::value::Wtf8> for PropertyKey {
fn from(text: crate::value::Wtf8) -> PropertyKey {
PropertyKey::String(text)
}
}
impl Trace for PropertyKey {
fn trace(&self, tracer: &mut Tracer) {
if let PropertyKey::Symbol(symbol) = self {
tracer.visit(symbol);
}
}
}
pub struct ObjectData {
pub proto: Option<Gc<JsObject>>,
pub props: Vec<(PropertyKey, Property)>,
pub kind: ObjectKind,
pub extensible: bool,
pub elements_writable: bool,
pub length_writable: bool,
pub home_object: Option<Gc<JsObject>>,
pub class_constructor: bool,
pub constructible: bool,
}
impl Trace for ObjectData {
fn trace(&self, tracer: &mut Tracer) {
if let Some(proto) = &self.proto {
tracer.visit(proto);
}
if let Some(home) = &self.home_object {
tracer.visit(home);
}
for (key, property) in &self.props {
key.trace(tracer);
property.trace(tracer);
}
self.kind.trace(tracer);
}
}
pub struct JsObject {
data: RefCell<ObjectData>,
}
impl JsObject {
fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
JsObject {
data: RefCell::new(ObjectData {
proto,
props: Vec::new(),
kind,
extensible: true,
elements_writable: true,
length_writable: true,
home_object: None,
class_constructor: false,
constructible: false,
}),
}
}
pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
}
pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
Gc::new(
heap,
JsObject::new(
ObjectKind::Array {
elements: Vec::with_capacity(capacity),
length: 0,
},
proto,
),
)
}
pub fn function(
heap: &js_gc::Heap,
proto: Option<Gc<JsObject>>,
callable: Callable,
) -> Gc<JsObject> {
Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
}
pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
f(&self.data.borrow())
}
pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
f(&mut self.data.borrow_mut())
}
pub fn is_callable(&self) -> bool {
match &self.data.borrow().kind {
ObjectKind::Function(_) => true,
ObjectKind::Proxy(state) => state.borrow().callable,
_ => false,
}
}
pub fn is_constructor(&self) -> bool {
let data = self.data.borrow();
match &data.kind {
ObjectKind::Function(_) => data.constructible,
ObjectKind::Proxy(state) => state.borrow().constructible,
_ => false,
}
}
pub fn set_constructible(&self, yes: bool) {
self.data.borrow_mut().constructible = yes;
}
pub fn proxy_state(&self) -> Option<ProxyRef> {
match &self.data.borrow().kind {
ObjectKind::Proxy(state) => Some(state.clone()),
_ => None,
}
}
pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
let callable = target.is_callable();
let constructible = target.is_constructor();
Gc::new(
heap,
JsObject::new(
ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
callable,
constructible,
target: Some(target),
handler: Some(handler),
}))),
None,
),
)
}
pub fn proto(&self) -> Option<Gc<JsObject>> {
self.data.borrow().proto.clone()
}
pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
self.data.borrow_mut().proto = proto;
}
pub fn home_object(&self) -> Option<Gc<JsObject>> {
self.data.borrow().home_object.clone()
}
pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
let mut data = self.data.borrow_mut();
data.home_object = home.clone();
if home.is_some() {
data.constructible = false;
}
}
pub fn is_class_constructor(&self) -> bool {
self.data.borrow().class_constructor
}
pub fn set_class_constructor(&self, yes: bool) {
self.data.borrow_mut().class_constructor = yes;
}
pub fn array_elements(&self) -> Option<Vec<Value>> {
match &self.data.borrow().kind {
ObjectKind::Array { elements, .. } => Some(elements.clone()),
_ => None,
}
}
pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
let data = self.data.borrow();
let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
if let ObjectKind::Array { elements, .. } = &data.kind {
for (index, element) in elements.iter().enumerate() {
if matches!(element, Value::Hole) {
continue;
}
let key = PropertyKey::from(index.to_string());
if !out.iter().any(|(existing, _)| *existing == key) {
out.push((key, Property::data(element.clone())));
}
}
}
if matches!(data.kind, ObjectKind::Array { .. })
&& let Some(length) = self.array_length()
{
let key = PropertyKey::from("length");
if !out.iter().any(|(existing, _)| *existing == key) {
out.push((
key,
Property {
value: Some(length_value(length)),
writable: self.length_writable(),
enumerable: false,
configurable: false,
getter: None,
setter: None,
},
));
}
}
out
}
pub fn is_array(&self) -> bool {
match &self.data.borrow().kind {
ObjectKind::Array { .. } => true,
ObjectKind::Proxy(state) => state
.borrow()
.target
.as_ref()
.is_some_and(|target| target.is_array()),
_ => false,
}
}
pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
match &self.data.borrow().kind {
ObjectKind::RegExp(data) => Some(data.clone()),
_ => None,
}
}
pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
match &self.data.borrow().kind {
ObjectKind::DisposableStack(state) => Some(state.clone()),
_ => None,
}
}
pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
}
pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
self.data.borrow_mut().kind = ObjectKind::RegExp(data);
}
pub fn is_regexp(&self) -> bool {
matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
}
pub fn array_length(&self) -> Option<usize> {
match &self.data.borrow().kind {
ObjectKind::Array { length, .. } => Some(*length),
_ => None,
}
}
pub fn array_get(&self, index: usize) -> Option<Value> {
match &self.data.borrow().kind {
ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
_ => None,
}
}
pub fn array_push(&self, value: Value) -> usize {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements, length } => {
elements.push(value);
*length = elements.len();
*length
}
_ => 0,
}
}
pub fn array_set(&self, index: usize, value: Value) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements, length } => {
if index >= *length {
if index + 1 > ARRAY_ELEMENT_LIMIT {
return false;
}
elements.resize(index + 1, Value::Hole);
*length = elements.len();
} else if index >= elements.len() {
elements.resize(index + 1, Value::Hole);
}
elements[index] = value;
true
}
_ => false,
}
}
pub fn array_store(&self, index: usize, value: Value) -> bool {
if self.elements_writable() {
return self.array_set(index, value);
}
if self.element_attributes(index as u32).is_some() {
return !self.element_is_locked(index as u32) && self.array_set(index, value);
}
false
}
pub fn array_push_hole(&self) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements, length } => {
elements.push(Value::Hole);
*length = elements.len();
true
}
_ => false,
}
}
pub fn array_set_length(&self, new_length: usize) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements, length } => {
if new_length < *length {
elements.truncate(new_length);
}
*length = new_length;
true
}
_ => false,
}
}
pub fn array_truncate(&self, new_length: usize) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements, length } => {
if new_length < elements.len() {
elements.truncate(new_length);
}
if new_length < *length {
*length = new_length;
}
true
}
_ => false,
}
}
pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
let data = self.data.borrow();
data.props
.iter()
.find(|(existing, _)| existing == key)
.map(|(_, property)| property.clone())
}
pub fn own_property(&self, name: &str) -> Option<Property> {
self.own_property_key(&PropertyKey::from(name))
}
pub fn has_own_key(&self, key: &PropertyKey) -> bool {
let data = self.data.borrow();
data.props.iter().any(|(existing, _)| existing == key)
}
pub fn has_own(&self, name: &str) -> bool {
self.has_own_key(&PropertyKey::from(name))
}
pub fn define_key(&self, key: &PropertyKey, property: Property) {
let mut data = self.data.borrow_mut();
match data.props.iter_mut().find(|(existing, _)| existing == key) {
Some((_, slot)) => *slot = property,
None => data.props.push((key.clone(), property)),
}
}
pub fn define(&self, name: &str, property: Property) {
self.define_key(&PropertyKey::from(name), property);
}
pub fn define_data(&self, name: &str, value: Value) {
self.define(name, Property::data(value));
}
pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
self.define_key(key, Property::data(value));
}
pub fn write_value(&self, name: &str, value: Value) -> bool {
self.write_value_key(&PropertyKey::from(name), value)
}
pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
let mut data = self.data.borrow_mut();
let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
else {
return false;
};
if property.is_accessor() || !property.writable {
return false;
}
property.value = Some(value);
true
}
pub fn delete(&self, name: &str) -> bool {
self.delete_key(&PropertyKey::from(name))
}
pub fn delete_key(&self, key: &PropertyKey) -> bool {
let mut data = self.data.borrow_mut();
match data.props.iter().position(|(existing, _)| existing == key) {
Some(index) => {
if data.props[index].1.configurable {
data.props.remove(index);
true
} else {
false
}
}
None => true,
}
}
pub fn is_extensible(&self) -> bool {
self.data.borrow().extensible
}
pub fn set_extensible(&self, extensible: bool) {
self.data.borrow_mut().extensible = extensible;
}
pub fn elements_writable(&self) -> bool {
self.data.borrow().elements_writable
}
pub fn length_writable(&self) -> bool {
self.data.borrow().length_writable
}
pub fn set_length_writable(&self, writable: bool) {
self.data.borrow_mut().length_writable = writable;
}
pub fn set_elements_writable(&self, writable: bool) {
self.data.borrow_mut().elements_writable = writable;
}
pub fn element_attributes(&self, index: u32) -> Option<Property> {
self.own_property(&index.to_string())
}
pub fn element_is_undeletable(&self, index: u32) -> bool {
if !self.elements_writable() {
return true;
}
self.element_attributes(index)
.is_some_and(|property| !property.configurable)
}
pub fn element_is_locked(&self, index: u32) -> bool {
if !self.elements_writable() {
return true;
}
self.element_attributes(index)
.is_some_and(|property| !property.writable && !property.configurable)
}
pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
self.data
.borrow()
.props
.iter()
.filter_map(|(key, _)| key.as_wtf8().cloned())
.collect()
}
pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
self.data
.borrow()
.props
.iter()
.filter(|(_, property)| property.enumerable)
.filter_map(|(key, _)| key.as_wtf8().cloned())
.collect()
}
pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
self.data
.borrow()
.props
.iter()
.filter_map(|(key, _)| match key {
PropertyKey::Symbol(symbol) => Some(symbol.clone()),
PropertyKey::String(_) => None,
})
.collect()
}
pub fn own_property_keys(&self) -> Vec<PropertyKey> {
let data = self.data.borrow();
let mut strings: Vec<PropertyKey> = Vec::new();
let mut symbols: Vec<PropertyKey> = Vec::new();
for (key, _) in &data.props {
if key.is_symbol() {
symbols.push(key.clone());
} else {
strings.push(key.clone());
}
}
strings.extend(symbols);
strings
}
pub fn chain(&self) -> Vec<Gc<JsObject>> {
let mut out = Vec::new();
let mut proto = self.proto();
while let Some(object) = proto {
proto = object.proto();
out.push(object);
}
out
}
}
pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => a.ptr_eq(b),
_ => false,
}
}
pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
if let Some(property) = object.own_property_key(key) {
return Some(property);
}
if object.typed_array_parts().is_some() {
let index = key.as_str().and_then(array_index)?;
let in_range = (index as usize) < object.typed_array_length()?;
return match object.typed_array_element(index as usize) {
Some(value) if in_range => Some(Property::data(value)),
_ => None,
};
}
if !object.is_array() {
return None;
}
let text = key.as_str()?;
if text == "length" {
return Some(Property {
value: Some(length_value(object.array_length()?)),
writable: object.length_writable(),
enumerable: false,
configurable: false,
getter: None,
setter: None,
});
}
let index = array_index(text)?;
match object.array_get(index as usize) {
Some(Value::Hole) | None => None,
Some(value) => Some(Property::data(value)),
}
}
pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
own_property_including_array(object, key).is_some()
}
pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
if let Some(property) = own_property_including_array(object, key) {
return Some((object.clone(), property));
}
for ancestor in object.chain() {
if let Some(property) = own_property_including_array(&ancestor, key) {
return Some((ancestor, property));
}
}
None
}
pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
lookup_key(object, &PropertyKey::from(name))
}
pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;
pub fn length_value(length: usize) -> Value {
if length <= i32::MAX as usize {
Value::Int(length as i32)
} else {
Value::Float(length as f64)
}
}
pub fn index_value(index: usize) -> Value {
length_value(index)
}
pub fn array_index(key: &str) -> Option<u32> {
if key.is_empty() || key.len() > 10 {
return None;
}
let bytes = key.as_bytes();
if !bytes.iter().all(u8::is_ascii_digit) {
return None;
}
if bytes[0] == b'0' && bytes.len() != 1 {
return None;
}
let value: u32 = key.parse().ok()?;
(value < u32::MAX).then_some(value)
}
impl Trace for JsObject {
fn trace(&self, tracer: &mut Tracer) {
self.data.borrow().trace(tracer);
}
}