1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
use super::{AsContext, AsContextMut, Stored};
use crate::{
collections::arena::ArenaIndex,
core::{UntypedVal, ValType},
value::WithType,
Val,
};
use core::{fmt, fmt::Display, ptr::NonNull};
/// A raw index to a global variable entity.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct GlobalIdx(u32);
impl ArenaIndex for GlobalIdx {
fn into_usize(self) -> usize {
self.0 as usize
}
fn from_usize(value: usize) -> Self {
let value = value.try_into().unwrap_or_else(|error| {
panic!("index {value} is out of bounds as global index: {error}")
});
Self(value)
}
}
/// An error that may occur upon operating on global variables.
#[derive(Debug)]
#[non_exhaustive]
pub enum GlobalError {
/// Occurs when trying to write to an immutable global variable.
ImmutableWrite,
/// Occurs when trying writing a value with mismatching type to a global variable.
TypeMismatch {
/// The type of the global variable.
expected: ValType,
/// The type of the new value that mismatches the type of the global variable.
encountered: ValType,
},
/// Occurs when a global type does not satisfy the constraints of another.
UnsatisfyingGlobalType {
/// The unsatisfying [`GlobalType`].
unsatisfying: GlobalType,
/// The required [`GlobalType`].
required: GlobalType,
},
}
#[cfg(feature = "std")]
impl std::error::Error for GlobalError {}
impl Display for GlobalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::ImmutableWrite => write!(f, "tried to write to immutable global variable"),
Self::TypeMismatch {
expected,
encountered,
} => {
write!(
f,
"type mismatch upon writing global variable. \
expected {expected:?} but encountered {encountered:?}.",
)
}
Self::UnsatisfyingGlobalType {
unsatisfying,
required,
} => {
write!(
f,
"global type {unsatisfying:?} does not \
satisfy requirements of {required:?}",
)
}
}
}
}
/// The mutability of a global variable.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Mutability {
/// The value of the global variable is a constant.
Const,
/// The value of the global variable is mutable.
Var,
}
impl Mutability {
/// Returns `true` if this mutability is [`Mutability::Const`].
pub fn is_const(&self) -> bool {
matches!(self, Self::Const)
}
/// Returns `true` if this mutability is [`Mutability::Var`].
pub fn is_mut(&self) -> bool {
matches!(self, Self::Var)
}
}
/// The type of a global variable.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct GlobalType {
/// The value type of the global variable.
content: ValType,
/// The mutability of the global variable.
mutability: Mutability,
}
impl GlobalType {
/// Creates a new [`GlobalType`] from the given [`ValType`] and [`Mutability`].
pub fn new(content: ValType, mutability: Mutability) -> Self {
Self {
content,
mutability,
}
}
/// Returns the [`ValType`] of the global variable.
pub fn content(&self) -> ValType {
self.content
}
/// Returns the [`Mutability`] of the global variable.
pub fn mutability(&self) -> Mutability {
self.mutability
}
/// Checks if `self` satisfies the given `GlobalType`.
///
/// # Errors
///
/// - If the initial limits of the `required` [`GlobalType`] are greater than `self`.
/// - If the maximum limits of the `required` [`GlobalType`] are greater than `self`.
pub(crate) fn satisfies(&self, required: &GlobalType) -> Result<(), GlobalError> {
if self != required {
return Err(GlobalError::UnsatisfyingGlobalType {
unsatisfying: *self,
required: *required,
});
}
Ok(())
}
}
/// A global variable entity.
#[derive(Debug)]
pub struct GlobalEntity {
/// The current value of the global variable.
value: UntypedVal,
/// The type of the global variable.
ty: GlobalType,
}
impl GlobalEntity {
/// Creates a new global entity with the given initial value and mutability.
pub fn new(initial_value: Val, mutability: Mutability) -> Self {
Self {
ty: GlobalType::new(initial_value.ty(), mutability),
value: initial_value.into(),
}
}
/// Returns the [`GlobalType`] of the global variable.
pub fn ty(&self) -> GlobalType {
self.ty
}
/// Sets a new value to the global variable.
///
/// # Errors
///
/// - If the global variable is immutable.
/// - If there is a type mismatch between the global variable and the new value.
pub fn set(&mut self, new_value: Val) -> Result<(), GlobalError> {
if !self.ty().mutability().is_mut() {
return Err(GlobalError::ImmutableWrite);
}
if self.ty().content() != new_value.ty() {
return Err(GlobalError::TypeMismatch {
expected: self.ty().content(),
encountered: new_value.ty(),
});
}
self.set_untyped(new_value.into());
Ok(())
}
/// Sets a new untyped value for the global variable.
///
/// # Note
///
/// This is an inherently unsafe API and only exists to allow
/// for efficient `global.set` through the interpreter which is
/// safe since the interpreter only handles validated Wasm code
/// where the checks in [`Global::set`] cannot fail.
pub(crate) fn set_untyped(&mut self, new_value: UntypedVal) {
self.value = new_value;
}
/// Returns the current value of the global variable.
pub fn get(&self) -> Val {
self.get_untyped().with_type(self.ty().content())
}
/// Returns the current untyped value of the global variable.
pub(crate) fn get_untyped(&self) -> UntypedVal {
self.value
}
/// Returns a pointer to the untyped value of the global variable.
pub(crate) fn get_untyped_ptr(&mut self) -> NonNull<UntypedVal> {
NonNull::from(&mut self.value)
}
}
/// A Wasm global variable reference.
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Global(Stored<GlobalIdx>);
impl Global {
/// Creates a new stored global variable reference.
///
/// # Note
///
/// This API is primarily used by the [`Store`] itself.
///
/// [`Store`]: [`crate::Store`]
pub(super) fn from_inner(stored: Stored<GlobalIdx>) -> Self {
Self(stored)
}
/// Returns the underlying stored representation.
pub(super) fn as_inner(&self) -> &Stored<GlobalIdx> {
&self.0
}
/// Creates a new global variable to the store.
pub fn new(mut ctx: impl AsContextMut, initial_value: Val, mutability: Mutability) -> Self {
ctx.as_context_mut()
.store
.inner
.alloc_global(GlobalEntity::new(initial_value, mutability))
}
/// Returns the [`GlobalType`] of the global variable.
pub fn ty(&self, ctx: impl AsContext) -> GlobalType {
ctx.as_context().store.inner.resolve_global(self).ty()
}
/// Sets a new value to the global variable.
///
/// # Errors
///
/// - If the global variable is immutable.
/// - If there is a type mismatch between the global variable and the new value.
///
/// # Panics
///
/// Panics if `ctx` does not own this [`Global`].
pub fn set(&self, mut ctx: impl AsContextMut, new_value: Val) -> Result<(), GlobalError> {
ctx.as_context_mut()
.store
.inner
.resolve_global_mut(self)
.set(new_value)
}
/// Returns the current value of the global variable.
///
/// # Panics
///
/// Panics if `ctx` does not own this [`Global`].
pub fn get(&self, ctx: impl AsContext) -> Val {
ctx.as_context().store.inner.resolve_global(self).get()
}
}