Truly independent web browser
LibJS: Expose host classes, modules and errors to Rust embedders
Shannon Bootha0547bd903ad
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex f3707bac0a9..539bd557972 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -9,6 +9,9 @@//! the runtime only through this module (Meta/Linters/check_libjs_rust_api.py), so the rest of the crate stays the//! runtime's own business.+pub use crate::embedding::abi_types::{completion_into_abi, object_from_abi, vm_from_abi};+pub use crate::embedding::host::host_function::HostFunction;+pub use crate::embedding::host::host_module::{HostModule, host_class_of as host_module_class_of};pub use crate::embedding::host::host_object::{HostObject, host_class_of, host_data_of, is_host_instance_of};pub use crate::gc::class::ExternalMemorySize;pub use crate::gc::defer_gc::DeferGc;@@ -19,32 +22,45 @@ pub use crate::gc::root::{MarkedVec, Root};pub use crate::gc::visitor::{Trace, Visitor};pub use crate::gc::weak::GcWeak;pub use crate::interpreter::vm::{TypeErrorRealmScope, Vm};-pub use crate::layout::cell::Gc;+pub use crate::layout::cell::{CellHeader, CellKind, Gc};pub use crate::layout::function_object::FunctionObject;-pub use crate::layout::host_class::JSHostClass;+pub use crate::layout::host_class::{+ JS_HOST_CLASS_FUNCTION, JS_HOST_CLASS_HAS_CONSTRUCTOR, JS_HOST_CLASS_MODULE,+ JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE, JS_HOST_CLASS_OBJECT, JS_RESOLVED_BINDING_BINDING_NAME,+ JS_RESOLVED_BINDING_NULL, JSCompletion, JSGetCacheMetadata, JSHostClass, JSHostFunctionHooks, JSHostModuleHooks,+ JSHostObjectHooks, JSModule, JSObject, JSPromiseCapability, JSPropertyDescriptor, JSPropertyKey, JSResolvedBinding,+ JSSetCacheMetadata, JSStringSink, JSVM, JSValue, JSValueSink,+};pub use crate::layout::value::Value;pub use crate::layout_forward::{RawNativeFunctionPointer, RawNativeFunctionResult};pub use crate::raw_native;pub use crate::runtime::abstract_operations::{call, construct, get_function_realm};+pub use crate::runtime::agent::agent_can_suspend;pub use crate::runtime::array::Array;pub use crate::runtime::array_buffer::{- ArrayBuffer, DataBlock, Order as ArrayBufferOrder, Shared as ArrayBufferShared, clone_array_buffer,- detach_array_buffer,+ ArrayBuffer, DataBlock, DataBlockStorage, ExternalPrimitiveStorage, Order as ArrayBufferOrder,+ Shared as ArrayBufferShared, clone_array_buffer, detach_array_buffer,};+pub use crate::runtime::big_int::BigInt;pub use crate::runtime::completion::{Must, Throw, ThrowCompletionOr};pub use crate::runtime::data_view::{DataView, DataViewWithBufferWitness, get_view_byte_length, is_view_out_of_bounds,make_data_view_with_buffer_witness_record,};-pub use crate::runtime::error::ErrorKind;+pub use crate::runtime::environment::InitializeBindingHint;+pub use crate::runtime::error::{Error, ErrorKind};+pub use crate::runtime::error_data::CompactTraceback;pub use crate::runtime::error_types::ErrorType;pub use crate::runtime::intrinsics::Intrinsics;pub use crate::runtime::iterator::{IteratorHint, IteratorRecord, create_iterator_result_object, get_iterator, get_iterator_from_method_impl,- iterator_complete, iterator_next, iterator_step_value, iterator_value,+ iterator_complete, iterator_next, iterator_step_value, iterator_to_list, iterator_value,};+pub use crate::runtime::module::Module;+pub use crate::runtime::module_environment::ModuleEnvironment;+pub use crate::runtime::module_request::ModuleRequest;pub use crate::runtime::native_function::{NativeFunction, RawNativeFunction};-pub use crate::runtime::object::Object;+pub use crate::runtime::object::{IntegrityLevel, Object};pub use crate::runtime::primitive_string::PrimitiveString;pub use crate::runtime::promise::{Promise, PromiseState, RejectionOperation};pub use crate::runtime::promise_capability::{PromiseCapability, new_promise_capability};diff --git a/Libraries/LibJS/Rust/src/embedding/abi_types.rs b/Libraries/LibJS/Rust/src/embedding/abi_types.rsindex ccb336038ed..3bd9319b0bc 100644--- a/Libraries/LibJS/Rust/src/embedding/abi_types.rs+++ b/Libraries/LibJS/Rust/src/embedding/abi_types.rs@@ -168,6 +168,16 @@ pub unsafe fn vm_from_abi<'vm>(vm: *mut JSVM) -> &'vm Vm {unsafe { vm.cast::<Vm>().as_ref() }}+/// The object of any class at the address of a JSObject the ABI passes.+///+/// # Safety+///+/// `object` must be the address of a live object.+pub unsafe fn object_from_abi(object: *mut JSObject) -> Gc<Object> {+ // SAFETY: The caller guarantees that the pointer is the address of a live object.+ unsafe { cell_from_abi(object) }+}+/// The address of an object of any class, as the JSObject the ABI passes.pub fn object_into_abi<T: Extends<Object>>(object: Gc<T>) -> *mut JSObject {cell_into_abi(object.upcast::<Object>())diff --git a/Libraries/LibJS/Rust/src/embedding/host/class_table.rs b/Libraries/LibJS/Rust/src/embedding/host/class_table.rsindex dbdb5e74bc6..004dbcfe36f 100644--- a/Libraries/LibJS/Rust/src/embedding/host/class_table.rs+++ b/Libraries/LibJS/Rust/src/embedding/host/class_table.rs@@ -20,7 +20,8 @@ use crate::layout::host_class::{JS_HOST_CLASS_NOT_ELIGIBLE_FOR_OWN_PROPERTY_ENUMERATION_FAST_PATH, JS_HOST_CLASS_OBJECT,JS_HOST_CLASS_REQUIRES_SLOW_ADD_OWN_PROPERTY, JS_HOST_CLASS_SHARES_ALLOCATOR_WITH_PARENT,JS_PROPERTY_LOOKUP_PHASE_OWN_PROPERTY, JS_PROPERTY_LOOKUP_PHASE_PROTOTYPE_CHAIN, JSCompletion, JSGetCacheMetadata,- JSHostArrayHooks, JSHostClass, JSHostFunctionHooks, JSHostObjectHooks, JSObject, JSSetCacheMetadata,+ JSHostArrayHooks, JSHostClass, JSHostFunctionHooks, JSHostModuleHooks, JSHostObjectHooks, JSObject,+ JSSetCacheMetadata,};use crate::layout::object::Object;use crate::runtime::completion::ThrowCompletionOr;@@ -74,7 +75,41 @@ pub fn host_class_into_abi(table: &'static JSHostClass) -> *const JSHostClass {core::ptr::from_ref(table)}+// SAFETY: A class and its hooks are constant data that lives as long as the process, which no thread writes.+unsafe impl Sync for JSHostClass {}+// SAFETY: As for the class.+unsafe impl Sync for JSHostObjectHooks {}+// SAFETY: As for the class.+unsafe impl Sync for JSHostFunctionHooks {}+// SAFETY: As for the class.+unsafe impl Sync for JSHostModuleHooks {}+impl JSHostClass {+ /// A class of the kind, for an embedder written in Rust, as JS::make_host_class() makes one for C++. `hooks` is the+ /// hook struct of the kind, which must live as long as the process.+ pub const fn new(+ kind: u8,+ name: &'static str,+ parent: Option<&'static JSHostClass>,+ hooks: *const core::ffi::c_void,+ flags: u32,+ ) -> Self {+ Self {+ abi_version: JS_HOST_ABI_VERSION,+ kind,+ reserved: 0,+ flags,+ name: name.as_ptr().cast(),+ name_length: name.len(),+ parent: match parent {+ Some(parent) => parent,+ None => core::ptr::null(),+ },+ hooks,+ user_data: core::ptr::null(),+ }+ }+/// The address that identifies the class.pub fn identity(&'static self) -> usize {core::ptr::from_ref(self).addr()diff --git a/Libraries/LibJS/Rust/src/runtime/big_int.rs b/Libraries/LibJS/Rust/src/runtime/big_int.rsindex c19abad0043..47201e914c9 100644--- a/Libraries/LibJS/Rust/src/runtime/big_int.rs+++ b/Libraries/LibJS/Rust/src/runtime/big_int.rs@@ -40,10 +40,23 @@ impl BigInt {vm.heap().allocate(|_| Self::new(big_integer))}+ pub fn create_from_i64(vm: &Vm, value: i64) -> Gc<BigInt> {+ Self::create(vm, SignedBigInteger::from(value))+ }++ pub fn create_from_u64(vm: &Vm, value: u64) -> Gc<BigInt> {+ Self::create(vm, SignedBigInteger::from(value))+ }+pub fn big_integer(&self) -> &SignedBigInteger {&self.big_integer}+ /// The value, if it is an integer in the range of u64.+ pub fn to_u64_if_exact(&self) -> Option<u64> {+ u64::try_from(&self.big_integer).ok()+ }+pub fn to_utf16_string(&self) -> Utf16String {Utf16String::from_utf8(&format!("{}n", self.big_integer))}diff --git a/Libraries/LibJS/Rust/src/runtime/error.rs b/Libraries/LibJS/Rust/src/runtime/error.rsindex 0f637d02e85..c4606872d29 100644--- a/Libraries/LibJS/Rust/src/runtime/error.rs+++ b/Libraries/LibJS/Rust/src/runtime/error.rs@@ -174,6 +174,12 @@ impl Error {})}+ /// An error with `prototype`, as OrdinaryCreateFromConstructor creates one for an error type of the embedder,+ /// whose prototype the realm's intrinsics do not have.+ pub fn create_with_prototype(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) -> Gc<Error> {+ realm.create_object(vm, |_| Error::new(vm, Error::CLASS, prototype))+ }+pub fn create_with_message(vm: &Vm, realm: Gc<Realm>, message: Utf16String) -> Gc<Error> {let error = Error::create(vm, realm);error.set_message(vm, message);diff --git a/Libraries/LibJS/Rust/src/runtime/native_function.rs b/Libraries/LibJS/Rust/src/runtime/native_function.rsindex 218f9c50b6b..9c8ef7ee486 100644--- a/Libraries/LibJS/Rust/src/runtime/native_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_function.rs@@ -238,6 +238,13 @@ impl NativeFunction {)}+ /// The captures of the object, if it is a native function that create() or create_with_name() made with captures+ /// of type C, which tell such a function from all others, as an internal slot of its own would.+ pub fn captures_if<C: 'static>(object: &Object) -> Option<&C> {+ let function = crate::gc::class::downcast_ref::<Object, CapturingNativeFunction>(object)?;+ function.native_function.captures().downcast_ref::<C>()+ }+pub fn as_native_function_gc(&self) -> Gc<NativeFunction> {Gc::from_ref(self)}@@ -450,6 +457,9 @@ impl FunctionObject {/// The behaviour of a native function that captures state, which a CapturingNativeFunction calls.pub trait NativeFunctionBehaviour: Trace + 'static {fn call(&self, vm: &Vm) -> ThrowCompletionOr<Value>;++ /// The state the behaviour captures.+ fn captures(&self) -> &dyn core::any::Any;}/// A behaviour together with the state it captures. The behaviour is zero-sized, so the captures are all the state@@ -474,6 +484,10 @@ wherefn call(&self, vm: &Vm) -> ThrowCompletionOr<Value> {(self.behaviour)(vm, &self.captures)}++ fn captures(&self) -> &dyn core::any::Any {+ &self.captures+ }}/// A native function whose behaviour captures state.