feat: 添加 ArrayBuffer 全局构造器
This commit is contained in:
@@ -195,6 +195,8 @@ pub struct BuiltinWorld {
|
|||||||
pub map_proto: P<JsObject>,
|
pub map_proto: P<JsObject>,
|
||||||
pub regexp_constructor: P<JsObject>,
|
pub regexp_constructor: P<JsObject>,
|
||||||
pub regexp_proto: P<JsObject>,
|
pub regexp_proto: P<JsObject>,
|
||||||
|
pub array_buffer_constructor: P<JsObject>,
|
||||||
|
pub array_buffer_proto: P<JsObject>,
|
||||||
pub sym_match: P<JsObject>,
|
pub sym_match: P<JsObject>,
|
||||||
pub sym_replace: P<JsObject>,
|
pub sym_replace: P<JsObject>,
|
||||||
pub sym_search: P<JsObject>,
|
pub sym_search: P<JsObject>,
|
||||||
@@ -285,6 +287,8 @@ impl BuiltinWorld {
|
|||||||
make_pair(string_forge, shape_forge, "Map", si_prototype, si_constructor, si_name);
|
make_pair(string_forge, shape_forge, "Map", si_prototype, si_constructor, si_name);
|
||||||
let (regexp_proto, regexp_constructor) =
|
let (regexp_proto, regexp_constructor) =
|
||||||
make_pair(string_forge, shape_forge, "RegExp", si_prototype, si_constructor, si_name);
|
make_pair(string_forge, shape_forge, "RegExp", si_prototype, si_constructor, si_name);
|
||||||
|
let (array_buffer_proto, array_buffer_constructor) =
|
||||||
|
make_pair(string_forge, shape_forge, "ArrayBuffer", si_prototype, si_constructor, si_name);
|
||||||
|
|
||||||
let sym_match = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
let sym_match = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||||
let sym_replace = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
let sym_replace = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||||
@@ -322,10 +326,11 @@ impl BuiltinWorld {
|
|||||||
wire_ctor_proto(&date_constructor, &date_proto);
|
wire_ctor_proto(&date_constructor, &date_proto);
|
||||||
wire_ctor_proto(&set_constructor, &set_proto);
|
wire_ctor_proto(&set_constructor, &set_proto);
|
||||||
wire_ctor_proto(&map_constructor, &map_proto);
|
wire_ctor_proto(&map_constructor, &map_proto);
|
||||||
|
wire_ctor_proto(&array_buffer_constructor, &array_buffer_proto);
|
||||||
|
|
||||||
// Wire prototype chains: all constructor prototypes inherit from Object.prototype.
|
// Wire prototype chains: all constructor prototypes inherit from Object.prototype.
|
||||||
let obj_proto_val = JsValue::from_js_object(object_proto.as_ptr() as *mut JsObject);
|
let obj_proto_val = JsValue::from_js_object(object_proto.as_ptr() as *mut JsObject);
|
||||||
let non_object_protos: [&P<JsObject>; 11] = [
|
let non_object_protos: [&P<JsObject>; 12] = [
|
||||||
&array_proto,
|
&array_proto,
|
||||||
&function_proto,
|
&function_proto,
|
||||||
&string_proto,
|
&string_proto,
|
||||||
@@ -337,6 +342,7 @@ impl BuiltinWorld {
|
|||||||
&set_proto,
|
&set_proto,
|
||||||
&map_proto,
|
&map_proto,
|
||||||
®exp_proto,
|
®exp_proto,
|
||||||
|
&array_buffer_proto,
|
||||||
];
|
];
|
||||||
for proto in &non_object_protos {
|
for proto in &non_object_protos {
|
||||||
let p = proto.as_ptr() as *mut JsObject;
|
let p = proto.as_ptr() as *mut JsObject;
|
||||||
@@ -377,6 +383,8 @@ impl BuiltinWorld {
|
|||||||
map_proto,
|
map_proto,
|
||||||
regexp_constructor,
|
regexp_constructor,
|
||||||
regexp_proto,
|
regexp_proto,
|
||||||
|
array_buffer_constructor,
|
||||||
|
array_buffer_proto,
|
||||||
sym_match,
|
sym_match,
|
||||||
sym_replace,
|
sym_replace,
|
||||||
sym_search,
|
sym_search,
|
||||||
|
|||||||
@@ -188,6 +188,9 @@ impl JsObject {
|
|||||||
pub const OBJ_TYPE_BOOLEAN_OBJ: u8 = 3;
|
pub const OBJ_TYPE_BOOLEAN_OBJ: u8 = 3;
|
||||||
pub const OBJ_TYPE_NUMBER_OBJ: u8 = 4;
|
pub const OBJ_TYPE_NUMBER_OBJ: u8 = 4;
|
||||||
pub const OBJ_TYPE_STRING_OBJ: u8 = 5;
|
pub const OBJ_TYPE_STRING_OBJ: u8 = 5;
|
||||||
|
pub const OBJ_TYPE_ARRAY_BUFFER: u8 = 6;
|
||||||
|
pub const OBJ_TYPE_DATA_VIEW: u8 = 7;
|
||||||
|
pub const OBJ_TYPE_TYPED_ARRAY: u8 = 8;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn is_date_obj(&self) -> bool {
|
pub fn is_date_obj(&self) -> bool {
|
||||||
@@ -209,6 +212,18 @@ impl JsObject {
|
|||||||
pub fn is_string_obj(&self) -> bool {
|
pub fn is_string_obj(&self) -> bool {
|
||||||
self.type_tag == Self::OBJ_TYPE_STRING_OBJ
|
self.type_tag == Self::OBJ_TYPE_STRING_OBJ
|
||||||
}
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn is_array_buffer_obj(&self) -> bool {
|
||||||
|
self.type_tag == Self::OBJ_TYPE_ARRAY_BUFFER
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn is_data_view_obj(&self) -> bool {
|
||||||
|
self.type_tag == Self::OBJ_TYPE_DATA_VIEW
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn is_typed_array_obj(&self) -> bool {
|
||||||
|
self.type_tag == Self::OBJ_TYPE_TYPED_ARRAY
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new_empty(shape_id: ShapeId, proto: JsValue) -> Self {
|
pub fn new_empty(shape_id: ShapeId, proto: JsValue) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crate::bind_constructor_hash;
|
||||||
|
use crate::bindings::{apply_binding_table, configure_native_constructor};
|
||||||
|
use oxide_kernel::kernel::{KernelCore, KernelSession};
|
||||||
|
use oxide_types::object::JsObject;
|
||||||
|
|
||||||
|
pub fn bind_array_buffer(core: &Arc<KernelCore>, session: &KernelSession, global: &mut JsObject) {
|
||||||
|
let ctor_ptr = session.builtin_world().array_buffer_constructor.as_ptr() as *mut JsObject;
|
||||||
|
let ctor = unsafe { &mut *ctor_ptr };
|
||||||
|
let proto_ptr = session.builtin_world().array_buffer_proto.as_ptr() as *mut JsObject;
|
||||||
|
let proto = unsafe { &mut *proto_ptr };
|
||||||
|
|
||||||
|
configure_native_constructor(ctor, crate::builtins::array_buffer::array_buffer_constructor as *const (), 1);
|
||||||
|
|
||||||
|
apply_binding_table(
|
||||||
|
session.builtin_world(),
|
||||||
|
ctor,
|
||||||
|
core,
|
||||||
|
&[("isView", crate::builtins::array_buffer::array_buffer_is_view as *const (), 1)],
|
||||||
|
);
|
||||||
|
|
||||||
|
apply_binding_table(
|
||||||
|
session.builtin_world(),
|
||||||
|
proto,
|
||||||
|
core,
|
||||||
|
&[
|
||||||
|
("byteLength", crate::builtins::array_buffer::array_buffer_byte_length as *const (), 0),
|
||||||
|
("slice", crate::builtins::array_buffer::array_buffer_slice as *const (), 2),
|
||||||
|
("toString", crate::builtins::array_buffer::array_buffer_to_string as *const (), 0),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
bind_constructor_hash!(
|
||||||
|
core,
|
||||||
|
global,
|
||||||
|
"ArrayBuffer",
|
||||||
|
ctor_ptr,
|
||||||
|
crate::builtins::array_buffer::array_buffer_constructor,
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod bind_array;
|
pub mod bind_array;
|
||||||
|
pub mod bind_array_buffer;
|
||||||
pub mod bind_boolean;
|
pub mod bind_boolean;
|
||||||
pub mod bind_date;
|
pub mod bind_date;
|
||||||
pub mod bind_error;
|
pub mod bind_error;
|
||||||
@@ -87,6 +88,7 @@ pub fn init_kernel_builtins(core: &Arc<KernelCore>, session: &mut KernelSession)
|
|||||||
|
|
||||||
bind_object::bind_object(core, session, global);
|
bind_object::bind_object(core, session, global);
|
||||||
bind_array::bind_array(core, session, global);
|
bind_array::bind_array(core, session, global);
|
||||||
|
bind_array_buffer::bind_array_buffer(core, session, global);
|
||||||
bind_error::bind_error(core, session, global);
|
bind_error::bind_error(core, session, global);
|
||||||
bind_string::bind_string(core, session, global);
|
bind_string::bind_string(core, session, global);
|
||||||
bind_number::bind_number(core, session, global);
|
bind_number::bind_number(core, session, global);
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
use oxide_kernel::shape_forge::EMPTY_SHAPE_ID;
|
||||||
|
use oxide_types::object::{JsObject, NativeFnPtr, PropAttributes};
|
||||||
|
use oxide_types::value::JsValue;
|
||||||
|
|
||||||
|
use crate::coercion;
|
||||||
|
use crate::native::NativeResult;
|
||||||
|
use crate::vm::Vm;
|
||||||
|
|
||||||
|
const MAX_ARRAY_BUFFER_LENGTH: usize = 1 << 30;
|
||||||
|
|
||||||
|
macro_rules! native_try {
|
||||||
|
($expr:expr) => {
|
||||||
|
match $expr {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(err) => return NativeResult::Err(err),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_error(vm: &mut Vm, msg: &str) -> NativeResult {
|
||||||
|
NativeResult::Err(crate::builtins::error::create_type_error(vm, msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_index(vm: &mut Vm, value: JsValue) -> Result<usize, JsValue> {
|
||||||
|
let n = coercion::to_number(value, vm.kernel_core().string_forge().as_ref());
|
||||||
|
if n.is_nan() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
if !n.is_finite() || n < 0.0 || n > MAX_ARRAY_BUFFER_LENGTH as f64 {
|
||||||
|
return Err(crate::builtins::error::create_range_error(vm, "invalid ArrayBuffer length"));
|
||||||
|
}
|
||||||
|
Ok(n.trunc() as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_index(vm: &mut Vm, value: JsValue, len: usize) -> usize {
|
||||||
|
let n = coercion::to_number(value, vm.kernel_core().string_forge().as_ref());
|
||||||
|
if n.is_nan() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let int = n.trunc() as isize;
|
||||||
|
if int < 0 {
|
||||||
|
len.saturating_sub((-int) as usize)
|
||||||
|
} else {
|
||||||
|
(int as usize).min(len)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_named_prop(vm: &mut Vm, obj: &mut JsObject, name: &str, value: JsValue, attributes: PropAttributes) {
|
||||||
|
let si = vm.kernel_core().string_forge().intern(name).0;
|
||||||
|
let _ = vm.define_data_property(obj, si, value, attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_array_buffer(vm: &mut Vm, data: Vec<u8>) -> *mut JsObject {
|
||||||
|
let proto = vm.session().builtin_world().array_buffer_proto.as_ptr() as *mut JsObject;
|
||||||
|
let mut obj = JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::from_js_object(proto));
|
||||||
|
obj.type_tag = JsObject::OBJ_TYPE_ARRAY_BUFFER;
|
||||||
|
let len = data.len();
|
||||||
|
let data_ptr = Box::into_raw(Box::new(data));
|
||||||
|
// SAFETY: ArrayBuffer objects are not callable, so their native_fn slot is reused
|
||||||
|
// as an opaque Box<Vec<u8>> pointer, matching the existing RegExp storage pattern.
|
||||||
|
obj.set_native_fn(Some(unsafe { NativeFnPtr::from_raw(data_ptr as *const ()) }));
|
||||||
|
set_named_prop(
|
||||||
|
vm,
|
||||||
|
&mut obj,
|
||||||
|
"byteLength",
|
||||||
|
JsValue::int(len as i32),
|
||||||
|
PropAttributes::new(false, false, false),
|
||||||
|
);
|
||||||
|
vm.epoch().alloc(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn array_buffer_data_ptr(vm: &mut Vm, this_val: JsValue) -> Result<*mut Vec<u8>, JsValue> {
|
||||||
|
if !this_val.is_object() {
|
||||||
|
return Err(crate::builtins::error::create_type_error(
|
||||||
|
vm,
|
||||||
|
"ArrayBuffer method called on incompatible receiver",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let obj_ptr = this_val.as_js_object_ptr();
|
||||||
|
if obj_ptr.is_null() {
|
||||||
|
return Err(crate::builtins::error::create_type_error(vm, "ArrayBuffer internal state invalid"));
|
||||||
|
}
|
||||||
|
let obj = unsafe { &*obj_ptr };
|
||||||
|
if !obj.is_array_buffer_obj() {
|
||||||
|
return Err(crate::builtins::error::create_type_error(
|
||||||
|
vm,
|
||||||
|
"ArrayBuffer method called on incompatible receiver",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let Some(data_ptr) = obj.native_fn() else {
|
||||||
|
return Err(crate::builtins::error::create_type_error(vm, "ArrayBuffer internal state invalid"));
|
||||||
|
};
|
||||||
|
let data_ptr = data_ptr.as_ptr() as *mut Vec<u8>;
|
||||||
|
if data_ptr.is_null() {
|
||||||
|
return Err(crate::builtins::error::create_type_error(vm, "ArrayBuffer internal state invalid"));
|
||||||
|
}
|
||||||
|
Ok(data_ptr)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_buffer_constructor(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||||
|
let length = if args.len() > 1 {
|
||||||
|
match to_index(vm, vm.reg(args[1])) {
|
||||||
|
Ok(length) => length,
|
||||||
|
Err(err) => return NativeResult::Err(err),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
NativeResult::Ok(JsValue::from_js_object(new_array_buffer(vm, vec![0; length])))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_buffer_byte_length(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||||
|
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||||
|
let data_ptr = native_try!(array_buffer_data_ptr(vm, this_val));
|
||||||
|
NativeResult::Ok(JsValue::int(unsafe { (*data_ptr).len() } as i32))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_buffer_slice(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||||
|
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||||
|
let data_ptr = native_try!(array_buffer_data_ptr(vm, this_val));
|
||||||
|
let data = unsafe { &*data_ptr };
|
||||||
|
let len = data.len();
|
||||||
|
let start = if args.len() > 1 { normalize_index(vm, vm.reg(args[1]), len) } else { 0 };
|
||||||
|
let end = if args.len() > 2 { normalize_index(vm, vm.reg(args[2]), len) } else { len };
|
||||||
|
let end = end.max(start);
|
||||||
|
NativeResult::Ok(JsValue::from_js_object(new_array_buffer(vm, data[start..end].to_vec())))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_buffer_is_view(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||||
|
let value = if args.len() > 1 { vm.reg(args[1]) } else { JsValue::undefined() };
|
||||||
|
if !value.is_object() {
|
||||||
|
return NativeResult::Ok(JsValue::bool(false));
|
||||||
|
}
|
||||||
|
let ptr = value.as_js_object_ptr();
|
||||||
|
if ptr.is_null() {
|
||||||
|
return NativeResult::Ok(JsValue::bool(false));
|
||||||
|
}
|
||||||
|
let obj = unsafe { &*ptr };
|
||||||
|
NativeResult::Ok(JsValue::bool(obj.is_data_view_obj() || obj.is_typed_array_obj()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_buffer_to_string(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||||
|
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||||
|
if array_buffer_data_ptr(vm, this_val).is_err() {
|
||||||
|
return type_error(vm, "ArrayBuffer.prototype.toString called on incompatible receiver");
|
||||||
|
}
|
||||||
|
NativeResult::Ok(vm.intern("[object ArrayBuffer]"))
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod array;
|
pub mod array;
|
||||||
|
pub mod array_buffer;
|
||||||
pub mod boolean;
|
pub mod boolean;
|
||||||
pub mod date;
|
pub mod date;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
use oxide_compiler::compiler::Compiler;
|
||||||
|
use oxide_types::value::JsValue;
|
||||||
|
use oxide_vm::vm::Vm;
|
||||||
|
|
||||||
|
fn eval(vm: &mut Vm, source: &str) -> Result<JsValue, String> {
|
||||||
|
let allocator = oxide_parser::Allocator::default();
|
||||||
|
let program = oxide_parser::parse(&allocator, source).map_err(|e| format!("Parse error: {:?}", e))?;
|
||||||
|
let module = Compiler::new().compile(&program).map_err(|e| format!("Compile error: {}", e))?;
|
||||||
|
vm.run(&module)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_str(vm: &Vm, val: JsValue) -> String {
|
||||||
|
vm.kernel_core()
|
||||||
|
.string_forge()
|
||||||
|
.lookup(val.as_string_index())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_global_and_static_method_exist() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result =
|
||||||
|
eval(&mut vm, "typeof ArrayBuffer === 'function' && typeof ArrayBuffer.isView === 'function'").unwrap();
|
||||||
|
assert!(result.as_bool());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_constructor_sets_byte_length_property() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(&mut vm, "var buf = new ArrayBuffer(8); buf.byteLength").unwrap();
|
||||||
|
assert_eq!(result.as_int(), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_slice_returns_copied_buffer_with_length() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(&mut vm, "var buf = new ArrayBuffer(8); var slice = buf.slice(2, 6); slice.byteLength").unwrap();
|
||||||
|
assert_eq!(result.as_int(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_slice_normalizes_negative_indices() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(
|
||||||
|
&mut vm,
|
||||||
|
"var buf = new ArrayBuffer(8); var start = -4; var end = -1; buf.slice(start, end).byteLength",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.as_int(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_is_view_returns_false_for_buffer_and_plain_object() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(
|
||||||
|
&mut vm,
|
||||||
|
"var buf = new ArrayBuffer(8); ArrayBuffer.isView(buf) === false && ArrayBuffer.isView({}) === false",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.as_bool());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_negative_length_throws_range_error() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(&mut vm, "try { new ArrayBuffer(-1) } catch (e) { e instanceof RangeError }").unwrap();
|
||||||
|
assert!(result.as_bool());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn array_buffer_to_string_is_identifiable() {
|
||||||
|
let mut vm = Vm::new();
|
||||||
|
let result = eval(&mut vm, "var buf = new ArrayBuffer(1); buf.toString()").unwrap();
|
||||||
|
assert_eq!(to_str(&vm, result), "[object ArrayBuffer]");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user