Unified Value into js/sys

This commit is contained in:
Syrus Akbary
2023-02-10 16:20:47 -08:00
parent c9e18e8d57
commit a5e631c176
13 changed files with 29 additions and 474 deletions

View File

@@ -7,8 +7,8 @@ use crate::js::vm::VMExtern;
use crate::js::FunctionType;
use crate::js::RuntimeError;
use crate::js::TypedFunction;
use crate::js::Value;
use crate::store::{AsStoreMut, AsStoreRef, StoreMut};
use crate::value::Value;
use js_sys::{Array, Function as JSFunction};
use std::iter::FromIterator;
use wasm_bindgen::prelude::*;
@@ -618,6 +618,14 @@ impl Function {
Ok(TypedFunction::from_handle(self.clone()))
}
pub(crate) fn vm_funcref(&self, store: &impl AsStoreRef) -> VMFuncRef {
unimplemented!();
}
pub(crate) unsafe fn from_vm_funcref(store: &mut impl AsStoreMut, funcref: VMFuncRef) -> Self {
unimplemented!();
}
#[track_caller]
fn closures_unsupported_panic() -> ! {
unimplemented!("Closures (functions with captured environments) are currently unsupported with native functions. See: https://github.com/wasmerio/wasmer/issues/1840")

View File

@@ -1,12 +1,12 @@
use crate::js::exports::{ExportError, Exportable};
use crate::js::externals::Extern;
use crate::js::value::Value;
use crate::js::vm::{VMExtern, VMGlobal};
use crate::js::wasm_bindgen_polyfill::Global as JSGlobal;
use crate::js::GlobalType;
use crate::js::Mutability;
use crate::js::RuntimeError;
use crate::store::{AsStoreMut, AsStoreRef};
use crate::value::Value;
use wasm_bindgen::JsValue;
use wasmer_types::{RawValue, Type};
@@ -129,7 +129,7 @@ impl Global {
///
/// assert_eq!(g.get(), Value::I32(1));
/// ```
pub fn get(&self, store: &impl AsStoreRef) -> Value {
pub fn get(&self, store: &mut impl AsStoreMut) -> Value {
unsafe {
let value = self.handle.global.value();
let ty = self.handle.ty;

View File

@@ -1,10 +1,10 @@
use crate::js::exports::{ExportError, Exportable};
use crate::js::externals::Extern;
use crate::js::value::Value;
use crate::js::vm::{VMExtern, VMFunction, VMTable};
use crate::js::RuntimeError;
use crate::js::{FunctionType, TableType};
use crate::store::{AsStoreMut, AsStoreRef};
use crate::value::Value;
use js_sys::Function;
/// A WebAssembly `table` instance.

View File

@@ -421,8 +421,7 @@ macro_rules! import_namespace {
#[cfg(test)]
mod test {
use crate::js::{Global, Value};
use crate::store::Store;
use crate::{Global, Store, Value};
// use wasm_bindgen::*;
use wasm_bindgen_test::*;

View File

@@ -37,7 +37,6 @@ mod native;
pub(crate) mod store;
mod trap;
mod types;
mod value;
pub(crate) mod vm;
mod wasm_bindgen_polyfill;
@@ -59,8 +58,6 @@ pub use crate::js::types::{
ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability,
TableType, ValType,
};
pub use crate::js::value::Value;
pub use crate::js::value::Value as Val;
pub use wasmer_types::is_wasm;
// TODO: OnCalledAction is needed for asyncify. It will be refactored with https://github.com/wasmerio/wasmer/issues/3451

View File

@@ -1,8 +1,8 @@
//use crate::js::externals::Function;
// use crate::store::{Store, StoreObject};
// use crate::js::RuntimeError;
use crate::js::value::Value;
use crate::store::AsStoreRef;
use crate::value::Value;
use wasm_bindgen::JsValue;
pub use wasmer_types::{
ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability,
@@ -46,6 +46,7 @@ impl AsJs for Value {
Self::V128(f) => JsValue::from_f64(*f as f64),
Self::FuncRef(Some(func)) => func.handle.function.clone().into(),
Self::FuncRef(None) => JsValue::null(),
Self::ExternRef(_) => unimplemented!(),
}
}
}

View File

@@ -1,448 +0,0 @@
use std::convert::TryFrom;
use std::fmt;
use std::string::{String, ToString};
use wasmer_types::RawValue;
use wasmer_types::Type;
//use crate::ExternRef;
use crate::js::externals::function::Function;
use crate::store::AsStoreRef;
/// WebAssembly computations manipulate values of basic value types:
/// * Integers (32 or 64 bit width)
/// * Floating-point (32 or 64 bit width)
///
/// Spec: <https://webassembly.github.io/spec/core/exec/runtime.html#values>
#[derive(Clone, PartialEq)]
pub enum Value {
/// A 32-bit integer.
///
/// In Wasm integers are sign-agnostic, i.e. this can either be signed or unsigned.
I32(i32),
/// A 64-bit integer.
///
/// In Wasm integers are sign-agnostic, i.e. this can either be signed or unsigned.
I64(i64),
/// A 32-bit float.
F32(f32),
/// A 64-bit float.
F64(f64),
/// An `externref` value which can hold opaque data to the wasm instance itself.
//ExternRef(Option<ExternRef>),
/// A first-class reference to a WebAssembly function.
FuncRef(Option<Function>),
/// A 128-bit number
V128(u128),
}
macro_rules! accessors {
($bind:ident $(($variant:ident($ty:ty) $get:ident $unwrap:ident $cvt:expr))*) => ($(
/// Attempt to access the underlying value of this `Value`, returning
/// `None` if it is not the correct type.
pub fn $get(&self) -> Option<$ty> {
if let Self::$variant($bind) = self {
Some($cvt)
} else {
None
}
}
/// Returns the underlying value of this `Value`, panicking if it's the
/// wrong type.
///
/// # Panics
///
/// Panics if `self` is not of the right type.
pub fn $unwrap(&self) -> $ty {
self.$get().expect(concat!("expected ", stringify!($ty)))
}
)*)
}
impl Value {
/// Returns a null `externref` value.
pub fn null() -> Self {
Self::FuncRef(None)
}
/// Returns the corresponding [`Type`] for this `Value`.
pub fn ty(&self) -> Type {
match self {
Self::I32(_) => Type::I32,
Self::I64(_) => Type::I64,
Self::F32(_) => Type::F32,
Self::F64(_) => Type::F64,
Self::V128(_) => Type::V128,
//Self::ExternRef(_) => Type::ExternRef,
Self::FuncRef(_) => Type::FuncRef,
}
}
/// Converts the `Value` into a `f64`.
pub fn as_raw(&self, _store: &impl AsStoreRef) -> RawValue {
match *self {
Self::I32(i32) => RawValue { i32 },
Self::I64(i64) => RawValue { i64 },
Self::F32(f32) => RawValue { f32 },
Self::F64(f64) => RawValue { f64 },
Self::V128(u128) => RawValue { u128 },
Self::FuncRef(None) => RawValue { funcref: 0 },
Self::FuncRef(Some(ref f)) => RawValue {
funcref: f.handle.function.as_f64().unwrap_or(0_f64) as _,
},
// Self::ExternRef(Some(ref e)) => e.vm_externref().into_raw(),
// Self::ExternRef(None) => RawValue { externref: 0 },
}
}
/// Converts a `f64` to a `Value`.
///
/// # Safety
///
pub unsafe fn from_raw(_store: &impl AsStoreRef, ty: Type, raw: RawValue) -> Self {
match ty {
Type::I32 => Self::I32(raw.i32),
Type::I64 => Self::I64(raw.i64),
Type::F32 => Self::F32(raw.f32),
Type::F64 => Self::F64(raw.f64),
Type::V128 => Self::V128(raw.u128),
Type::FuncRef => {
unimplemented!();
// Self::FuncRef(VMFuncRef::from_raw(raw).map(|f| Function::from_vm_funcref(store, f)))
}
Type::ExternRef => {
unimplemented!();
// Self::ExternRef(
// VMExternRef::from_raw(raw).map(|e| ExternRef::from_vm_externref(store, e)),
// )
}
}
}
/// Checks whether a value can be used with the given context.
///
/// Primitive (`i32`, `i64`, etc) and null funcref/externref values are not
/// tied to a context and can be freely shared between contexts.
///
/// Externref and funcref values are tied to a context and can only be used
/// with that context.
pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool {
match self {
Self::I32(_)
| Self::I64(_)
| Self::F32(_)
| Self::F64(_)
| Self::V128(_)
//| Self::ExternRef(None)
| Self::FuncRef(None) => true,
//Self::ExternRef(Some(e)) => e.is_from_store(store),
Self::FuncRef(Some(f)) => f.is_from_store(store),
}
}
accessors! {
e
(I32(i32) i32 unwrap_i32 *e)
(I64(i64) i64 unwrap_i64 *e)
(F32(f32) f32 unwrap_f32 *e)
(F64(f64) f64 unwrap_f64 *e)
(V128(u128) v128 unwrap_v128 *e)
//(ExternRef(&Option<ExternRef>) externref unwrap_externref e)
(FuncRef(&Option<Function>) funcref unwrap_funcref e)
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::I32(v) => write!(f, "I32({:?})", v),
Self::I64(v) => write!(f, "I64({:?})", v),
Self::F32(v) => write!(f, "F32({:?})", v),
Self::F64(v) => write!(f, "F64({:?})", v),
Self::V128(v) => write!(f, "V128({:?})", v),
//Self::ExternRef(None) => write!(f, "Null ExternRef"),
//Self::ExternRef(Some(v)) => write!(f, "ExternRef({:?})", v),
Self::FuncRef(None) => write!(f, "Null FuncRef"),
Self::FuncRef(Some(v)) => write!(f, "FuncRef({:?})", v),
}
}
}
impl ToString for Value {
fn to_string(&self) -> String {
match self {
Self::I32(v) => v.to_string(),
Self::I64(v) => v.to_string(),
Self::F32(v) => v.to_string(),
Self::F64(v) => v.to_string(),
Self::V128(v) => v.to_string(),
//Self::ExternRef(_) => "externref".to_string(),
Self::FuncRef(_) => "funcref".to_string(),
}
}
}
impl From<u128> for Value {
fn from(val: u128) -> Self {
Self::V128(val)
}
}
impl From<i32> for Value {
fn from(val: i32) -> Self {
Self::I32(val)
}
}
impl From<u32> for Value {
fn from(val: u32) -> Self {
// In Wasm integers are sign-agnostic, so i32 is basically a 4 byte storage we can use for signed or unsigned 32-bit integers.
Self::I32(val as i32)
}
}
impl From<i64> for Value {
fn from(val: i64) -> Self {
Self::I64(val)
}
}
impl From<u64> for Value {
fn from(val: u64) -> Self {
// In Wasm integers are sign-agnostic, so i64 is basically an 8 byte storage we can use for signed or unsigned 64-bit integers.
Self::I64(val as i64)
}
}
impl From<f32> for Value {
fn from(val: f32) -> Self {
Self::F32(val)
}
}
impl From<f64> for Value {
fn from(val: f64) -> Self {
Self::F64(val)
}
}
impl From<Function> for Value {
fn from(val: Function) -> Self {
Self::FuncRef(Some(val))
}
}
impl From<Option<Function>> for Value {
fn from(val: Option<Function>) -> Self {
Self::FuncRef(val)
}
}
//impl From<ExternRef> for Value {
// fn from(val: ExternRef) -> Self {
// Self::ExternRef(Some(val))
// }
//}
//
//impl From<Option<ExternRef>> for Value {
// fn from(val: Option<ExternRef>) -> Self {
// Self::ExternRef(val)
// }
//}
const NOT_I32: &str = "Value is not of Wasm type i32";
const NOT_I64: &str = "Value is not of Wasm type i64";
const NOT_F32: &str = "Value is not of Wasm type f32";
const NOT_F64: &str = "Value is not of Wasm type f64";
const NOT_V128: &str = "Value is not of Wasm type u128";
const NOT_FUNCREF: &str = "Value is not of Wasm type funcref";
//const NOT_EXTERNREF: &str = "Value is not of Wasm type externref";
impl TryFrom<Value> for u128 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.v128().ok_or(NOT_V128)
}
}
impl TryFrom<Value> for i32 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.i32().ok_or(NOT_I32)
}
}
impl TryFrom<Value> for u32 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.i32().ok_or(NOT_I32).map(|int| int as Self)
}
}
impl TryFrom<Value> for i64 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.i64().ok_or(NOT_I64)
}
}
impl TryFrom<Value> for u64 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.i64().ok_or(NOT_I64).map(|int| int as Self)
}
}
impl TryFrom<Value> for f32 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.f32().ok_or(NOT_F32)
}
}
impl TryFrom<Value> for f64 {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
value.f64().ok_or(NOT_F64)
}
}
impl TryFrom<Value> for Option<Function> {
type Error = &'static str;
fn try_from(value: Value) -> Result<Self, Self::Error> {
match value {
Value::FuncRef(f) => Ok(f),
_ => Err(NOT_FUNCREF),
}
}
}
//impl TryFrom<Value> for Option<ExternRef> {
// type Error = &'static str;
//
// fn try_from(value: Value) -> Result<Self, Self::Error> {
// match value {
// Value::ExternRef(e) => Ok(e),
// _ => Err(NOT_EXTERNREF),
// }
// }
//}
#[cfg(tests)]
mod tests {
use super::*;
/*
fn test_value_i32_from_u32() {
let bytes = [0x00, 0x00, 0x00, 0x00];
let v = Value::<()>::from(u32::from_be_bytes(bytes));
assert_eq!(v, Value::I32(i32::from_be_bytes(bytes)));
let bytes = [0x00, 0x00, 0x00, 0x01];
let v = Value::<()>::from(u32::from_be_bytes(bytes));
assert_eq!(v, Value::I32(i32::from_be_bytes(bytes)));
let bytes = [0xAA, 0xBB, 0xCC, 0xDD];
let v = Value::<()>::from(u32::from_be_bytes(bytes));
assert_eq!(v, Value::I32(i32::from_be_bytes(bytes)));
let bytes = [0xFF, 0xFF, 0xFF, 0xFF];
let v = Value::<()>::from(u32::from_be_bytes(bytes));
assert_eq!(v, Value::I32(i32::from_be_bytes(bytes)));
}
fn test_value_i64_from_u64() {
let bytes = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let v = Value::<()>::from(u64::from_be_bytes(bytes));
assert_eq!(v, Value::I64(i64::from_be_bytes(bytes)));
let bytes = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01];
let v = Value::<()>::from(u64::from_be_bytes(bytes));
assert_eq!(v, Value::I64(i64::from_be_bytes(bytes)));
let bytes = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11];
let v = Value::<()>::from(u64::from_be_bytes(bytes));
assert_eq!(v, Value::I64(i64::from_be_bytes(bytes)));
let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
let v = Value::<()>::from(u64::from_be_bytes(bytes));
assert_eq!(v, Value::I64(i64::from_be_bytes(bytes)));
}
fn convert_value_to_i32() {
let value = Value::<()>::I32(5678);
let result = i32::try_from(value);
assert_eq!(result.unwrap(), 5678);
let value = Value::<()>::from(u32::MAX);
let result = i32::try_from(value);
assert_eq!(result.unwrap(), -1);
}
fn convert_value_to_u32() {
let value = Value::<()>::from(u32::MAX);
let result = u32::try_from(value);
assert_eq!(result.unwrap(), u32::MAX);
let value = Value::<()>::I32(-1);
let result = u32::try_from(value);
assert_eq!(result.unwrap(), u32::MAX);
}
fn convert_value_to_i64() {
let value = Value::<()>::I64(5678);
let result = i64::try_from(value);
assert_eq!(result.unwrap(), 5678);
let value = Value::<()>::from(u64::MAX);
let result = i64::try_from(value);
assert_eq!(result.unwrap(), -1);
}
fn convert_value_to_u64() {
let value = Value::<()>::from(u64::MAX);
let result = u64::try_from(value);
assert_eq!(result.unwrap(), u64::MAX);
let value = Value::<()>::I64(-1);
let result = u64::try_from(value);
assert_eq!(result.unwrap(), u64::MAX);
}
fn convert_value_to_f32() {
let value = Value::<()>::F32(1.234);
let result = f32::try_from(value);
assert_eq!(result.unwrap(), 1.234);
let value = Value::<()>::F64(1.234);
let result = f32::try_from(value);
assert_eq!(result.unwrap_err(), "Value is not of Wasm type f32");
}
fn convert_value_to_f64() {
let value = Value::<()>::F64(1.234);
let result = f64::try_from(value);
assert_eq!(result.unwrap(), 1.234);
let value = Value::<()>::F32(1.234);
let result = f64::try_from(value);
assert_eq!(result.unwrap_err(), "Value is not of Wasm type f64");
}
*/
}

View File

@@ -437,6 +437,7 @@ mod module;
mod native_type;
mod ptr;
mod store;
mod value;
#[cfg(feature = "sys")]
mod sys;
@@ -460,6 +461,7 @@ pub use ptr::{Memory32, Memory64, MemorySize, WasmPtr, WasmPtr64};
pub use store::{AsStoreMut, AsStoreRef, OnCalledHandler, Store, StoreId, StoreMut, StoreRef};
#[cfg(feature = "sys")]
pub use store::{TrapHandlerFn, Tunables};
pub use value::Value;
mod into_bytes;
pub use into_bytes::IntoBytes;

View File

@@ -423,9 +423,7 @@ impl Function {
)));
}
if !arg.is_from_store(store) {
return Err(RuntimeError::new(
"cross-`Store` values are not supported",
));
return Err(RuntimeError::new("cross-`Store` values are not supported"));
}
*slot = arg.as_raw(store);
}
@@ -613,7 +611,6 @@ impl Function {
VMFuncRef(vm_function.anyfunc.as_ptr())
}
#[cfg(feature = "compiler")]
pub(crate) unsafe fn from_vm_funcref(store: &mut impl AsStoreMut, funcref: VMFuncRef) -> Self {
let signature = store
.as_store_ref()

View File

@@ -1,10 +1,10 @@
use crate::store::{AsStoreMut, AsStoreRef};
use crate::sys::exports::{ExportError, Exportable};
use crate::sys::externals::Extern;
use crate::sys::value::Value;
use crate::sys::GlobalType;
use crate::sys::Mutability;
use crate::sys::RuntimeError;
use crate::value::Value;
use wasmer_vm::{InternalStoreHandle, StoreHandle, VMExtern, VMGlobal};
/// A WebAssembly `global` instance.
@@ -60,9 +60,7 @@ impl Global {
mutability: Mutability,
) -> Result<Self, RuntimeError> {
if !val.is_from_store(store) {
return Err(RuntimeError::new(
"cross-`Store` values are not supported",
));
return Err(RuntimeError::new("cross-`Store` values are not supported"));
}
let global = VMGlobal::new(GlobalType {
mutability,
@@ -164,9 +162,7 @@ impl Global {
/// ```
pub fn set(&self, store: &mut impl AsStoreMut, val: Value) -> Result<(), RuntimeError> {
if !val.is_from_store(store) {
return Err(RuntimeError::new(
"cross-`Store` values are not supported",
));
return Err(RuntimeError::new("cross-`Store` values are not supported"));
}
if self.ty(store).mutability != Mutability::Var {
return Err(RuntimeError::new("Attempted to set an immutable global"));

View File

@@ -306,7 +306,8 @@ macro_rules! import_namespace {
#[cfg(test)]
mod test {
use crate::store::{AsStoreMut, Store};
use crate::sys::{Global, Value};
use crate::sys::Global;
use crate::value::Value;
use wasmer_types::Type;
use wasmer_vm::VMExtern;

View File

@@ -7,7 +7,6 @@ mod instance;
pub(crate) mod module;
mod native;
mod tunables;
mod value;
pub use crate::sys::exports::{ExportError, Exportable, Exports, ExportsIterator};
pub use crate::sys::externals::{
@@ -19,7 +18,6 @@ pub use crate::sys::instance::{Instance, InstantiationError};
pub use crate::sys::native::TypedFunction;
pub use crate::sys::tunables::BaseTunables;
pub use crate::sys::value::Value;
pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Triple, HOST};
#[cfg(feature = "compiler")]
pub use wasmer_compiler::{

View File

@@ -3,7 +3,12 @@ use std::fmt;
use std::string::{String, ToString};
use wasmer_types::Type;
#[cfg(feature = "compiler")]
#[cfg(feature = "js")]
use crate::js::extern_ref::VMExternRef;
#[cfg(feature = "js")]
use crate::js::externals::function::VMFuncRef;
#[cfg(feature = "sys")]
use wasmer_vm::{VMExternRef, VMFuncRef};
use crate::ExternRef;
@@ -106,7 +111,6 @@ impl Value {
}
}
#[cfg(feature = "compiler")]
/// Converts a `RawValue` to a `Value`.
///
/// # Safety