use std::cell::RefCell;
use js_compile::bytecode::Function as CompiledFunction;
use js_gc::{Gc, Trace, Tracer};
use crate::value::{Cell, Value};
#[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 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,
},
}
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 { .. } => {}
}
}
}
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>>,
}
impl Trace for ClosureEnv {
fn trace(&self, tracer: &mut Tracer) {
for cell in &self.cells {
tracer.visit(cell);
}
}
}
pub enum ObjectKind {
Ordinary,
Array {
elements: Vec<Value>,
},
Function(Callable),
}
impl Trace for ObjectKind {
fn trace(&self, tracer: &mut Tracer) {
match self {
ObjectKind::Ordinary => {}
ObjectKind::Array { elements } => {
for element in elements {
element.trace(tracer);
}
}
ObjectKind::Function(callable) => callable.trace(tracer),
}
}
}
pub struct ObjectData {
pub proto: Option<Gc<JsObject>>,
pub props: Vec<(String, Property)>,
pub kind: ObjectKind,
pub extensible: bool,
pub elements_writable: bool,
}
impl Trace for ObjectData {
fn trace(&self, tracer: &mut Tracer) {
if let Some(proto) = &self.proto {
tracer.visit(proto);
}
for (_, property) in &self.props {
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,
}),
}
}
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),
},
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 {
matches!(self.data.borrow().kind, ObjectKind::Function(_))
}
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 array_elements(&self) -> Option<Vec<Value>> {
match &self.data.borrow().kind {
ObjectKind::Array { elements } => Some(elements.clone()),
_ => None,
}
}
pub fn is_array(&self) -> bool {
matches!(self.data.borrow().kind, ObjectKind::Array { .. })
}
pub fn array_length(&self) -> Option<usize> {
match &self.data.borrow().kind {
ObjectKind::Array { elements } => Some(elements.len()),
_ => 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 } => {
elements.push(value);
elements.len()
}
_ => 0,
}
}
pub fn array_set(&self, index: usize, value: Value) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements } => {
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 } => {
elements.push(Value::Hole);
true
}
_ => false,
}
}
pub fn array_set_length(&self, length: usize) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements } => {
elements.resize(length, Value::Hole);
true
}
_ => false,
}
}
pub fn array_truncate(&self, length: usize) -> bool {
match &mut self.data.borrow_mut().kind {
ObjectKind::Array { elements } => {
if length < elements.len() {
elements.truncate(length);
}
true
}
_ => false,
}
}
pub fn own_property(&self, name: &str) -> Option<Property> {
let data = self.data.borrow();
data.props
.iter()
.find(|(key, _)| key == name)
.map(|(_, property)| property.clone())
}
pub fn has_own(&self, name: &str) -> bool {
self.data.borrow().props.iter().any(|(key, _)| key == name)
}
pub fn define(&self, name: &str, property: Property) {
let mut data = self.data.borrow_mut();
match data.props.iter_mut().find(|(key, _)| key == name) {
Some((_, slot)) => *slot = property,
None => data.props.push((name.to_string(), property)),
}
}
pub fn define_data(&self, name: &str, value: Value) {
self.define(name, Property::data(value));
}
pub fn write_value(&self, name: &str, value: Value) -> bool {
let mut data = self.data.borrow_mut();
let Some((_, property)) = data.props.iter_mut().find(|(key, _)| key == name) else {
return false;
};
if property.is_accessor() || !property.writable {
return false;
}
property.value = Some(value);
true
}
pub fn delete(&self, name: &str) -> bool {
let mut data = self.data.borrow_mut();
match data.props.iter().position(|(key, _)| key == name) {
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 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_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<String> {
self.data
.borrow()
.props
.iter()
.map(|(key, _)| key.clone())
.collect()
}
pub fn own_enumerable_keys(&self) -> Vec<String> {
self.data
.borrow()
.props
.iter()
.filter(|(_, property)| property.enumerable)
.map(|(key, _)| key.clone())
.collect()
}
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 fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
if let Some(property) = object.own_property(name) {
return Some((object.clone(), property));
}
for ancestor in object.chain() {
if let Some(property) = ancestor.own_property(name) {
return Some((ancestor, property));
}
}
None
}
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);
}
}