A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add support for `structref` to the C and C++ APIs (#12915)
Nick Fitzgeraldf960e9af180a
diff --git a/crates/c-api/include/wasmtime/gc.h b/crates/c-api/include/wasmtime/gc.hindex eac86508e1..42eba19649 100644--- a/crates/c-api/include/wasmtime/gc.h+++ b/crates/c-api/include/wasmtime/gc.h@@ -126,6 +126,222 @@ WASM_API_EXTERN bool wasmtime_eqref_i31_get_s(wasmtime_context_t *context,const wasmtime_eqref_t *eqref,int32_t *dst);+// ============================================================================+// StructRef+// ============================================================================++/**+ * \brief Discriminant for storage types in struct/array field types.+ *+ * Extends #wasmtime_valkind_t with packed storage types+ * #WASMTIME_STORAGE_KIND_I8 and #WASMTIME_STORAGE_KIND_I16.+ */+typedef uint8_t wasmtime_storage_kind_t;++/// \brief An 8-bit packed integer (only valid inside struct/array fields).+#define WASMTIME_STORAGE_KIND_I8 9+/// \brief A 16-bit packed integer (only valid inside struct/array fields).+#define WASMTIME_STORAGE_KIND_I16 10++/**+ * \typedef wasmtime_field_type_t+ * \brief Convenience alias for #wasmtime_field_type+ *+ * \struct wasmtime_field_type+ * \brief Describes the type and mutability of a struct field or array element.+ */+typedef struct wasmtime_field_type {+ /// The storage type of this field. Use #WASMTIME_I32, #WASMTIME_I64,+ /// #WASMTIME_F32, etc. for value types, or #WASMTIME_STORAGE_KIND_I8 /+ /// #WASMTIME_STORAGE_KIND_I16 for packed types.+ wasmtime_storage_kind_t kind;+ /// Whether this field is mutable. `true` for mutable, `false` for+ /// immutable.+ bool mutable_;+} wasmtime_field_type_t;++/**+ * \brief An opaque handle to a WebAssembly struct type definition.+ *+ * A struct type describes the fields of a struct. It is used to create a+ * #wasmtime_struct_ref_pre_t, which can then allocate struct instances.+ *+ * Owned. Must be deleted with #wasmtime_struct_type_delete.+ */+typedef struct wasmtime_struct_type wasmtime_struct_type_t;++/**+ * \brief Create a new struct type.+ *+ * \param engine The engine to register the type with.+ * \param fields Pointer to an array of field type descriptors.+ * \param nfields Number of fields.+ *+ * \return Returns a new struct type, or NULL on error (e.g. invalid field+ * types).+ */+WASM_API_EXTERN wasmtime_struct_type_t *+wasmtime_struct_type_new(const wasm_engine_t *engine,+ const wasmtime_field_type_t *fields, size_t nfields);++/**+ * \brief Delete a struct type.+ */+WASM_API_EXTERN void wasmtime_struct_type_delete(wasmtime_struct_type_t *ty);++/**+ * \brief An opaque, pre-allocated, and registered struct layout for faster+ * allocation.+ *+ * Created from a #wasmtime_struct_type_t and a store context. Reusable for+ * allocating many struct instances of the same type.+ *+ * Owned. Must be deleted with #wasmtime_struct_ref_pre_delete.+ */+typedef struct wasmtime_struct_ref_pre wasmtime_struct_ref_pre_t;++/**+ * \brief Create a new struct pre-allocator.+ *+ * \param context The store context.+ * \param ty The struct type.+ *+ * \return Returns a new struct ref pre-allocator.+ */+WASM_API_EXTERN wasmtime_struct_ref_pre_t *+wasmtime_struct_ref_pre_new(wasmtime_context_t *context,+ const wasmtime_struct_type_t *ty);++/**+ * \brief Delete a struct pre-allocator.+ */+WASM_API_EXTERN void+wasmtime_struct_ref_pre_delete(wasmtime_struct_ref_pre_t *pre);++/**+ * \typedef wasmtime_structref_t+ * \brief Convenience alias for #wasmtime_structref+ *+ * \struct wasmtime_structref+ * \brief A WebAssembly `structref` value.+ *+ * This structure represents a reference to a GC struct. It is a subtype of+ * `eqref` and `anyref`.+ *+ * Values must be explicitly unrooted via #wasmtime_structref_unroot.+ */+typedef struct wasmtime_structref {+ /// Internal metadata.+ uint64_t store_id;+ /// Internal to Wasmtime.+ uint32_t __private1;+ /// Internal to Wasmtime.+ uint32_t __private2;+ /// Internal to Wasmtime.+ void *__private3;+} wasmtime_structref_t;++/// \brief Initialize the `ref` to a null `structref` value.+static inline void wasmtime_structref_set_null(wasmtime_structref_t *ref) {+ ref->store_id = 0;+}++/// \brief Returns whether the provided `ref` is a null `structref` value.+static inline bool wasmtime_structref_is_null(const wasmtime_structref_t *ref) {+ return ref->store_id == 0;+}++/**+ * \brief Allocate a new struct instance.+ *+ * \param context The store context.+ * \param pre The struct pre-allocator.+ * \param fields Pointer to array of field values (#wasmtime_val_t).+ * \param nfields Number of fields (must match the struct type).+ * \param out Receives the new structref on success.+ *+ * \return NULL on success, or a #wasmtime_error_t on failure.+ */+WASM_API_EXTERN wasmtime_error_t *wasmtime_structref_new(+ wasmtime_context_t *context, const wasmtime_struct_ref_pre_t *pre,+ const wasmtime_val_t *fields, size_t nfields, wasmtime_structref_t *out);++/**+ * \brief Clone a `structref`, creating a new root.+ */+WASM_API_EXTERN void+wasmtime_structref_clone(const wasmtime_structref_t *structref,+ wasmtime_structref_t *out);++/**+ * \brief Unroot a `structref` to allow garbage collection.+ */+WASM_API_EXTERN void wasmtime_structref_unroot(wasmtime_structref_t *ref);++/**+ * \brief Upcast a `structref` to an `anyref`.+ */+WASM_API_EXTERN void+wasmtime_structref_to_anyref(const wasmtime_structref_t *structref,+ wasmtime_anyref_t *out);++/**+ * \brief Upcast a `structref` to an `eqref`.+ */+WASM_API_EXTERN void+wasmtime_structref_to_eqref(const wasmtime_structref_t *structref,+ wasmtime_eqref_t *out);++/**+ * \brief Read a field from a struct.+ *+ * \param context The store context.+ * \param structref The struct to read from (not consumed).+ * \param index The field index.+ * \param out Receives the field value on success.+ *+ * \return NULL on success, or a #wasmtime_error_t on failure.+ */+WASM_API_EXTERN wasmtime_error_t *+wasmtime_structref_field(wasmtime_context_t *context,+ const wasmtime_structref_t *structref, size_t index,+ wasmtime_val_t *out);++/**+ * \brief Set a field of a struct.+ *+ * \param context The store context.+ * \param structref The struct to write to (not consumed).+ * \param index The field index.+ * \param val The value to write (not consumed; caller must still unroot if+ * applicable).+ *+ * \return NULL on success, or a #wasmtime_error_t on failure.+ */+WASM_API_EXTERN wasmtime_error_t *+wasmtime_structref_set_field(wasmtime_context_t *context,+ const wasmtime_structref_t *structref,+ size_t index, const wasmtime_val_t *val);++/**+ * \brief Test whether an `eqref` is a `structref`.+ *+ * Returns `false` for null references.+ */+WASM_API_EXTERN bool wasmtime_eqref_is_struct(wasmtime_context_t *context,+ const wasmtime_eqref_t *eqref);++/**+ * \brief Downcast an `eqref` to a `structref`.+ *+ * If the given `eqref` is a `structref`, a new root for it is stored in `out`+ * and `true` is returned. Otherwise `false` is returned and `out` is set to+ * null.+ */+WASM_API_EXTERN bool wasmtime_eqref_as_struct(wasmtime_context_t *context,+ const wasmtime_eqref_t *eqref,+ wasmtime_structref_t *out);+#ifdef __cplusplus} // extern "C"#endifdiff --git a/crates/c-api/include/wasmtime/gc.hh b/crates/c-api/include/wasmtime/gc.hhindex e404f471ad..d92445e59c 100644--- a/crates/c-api/include/wasmtime/gc.hh+++ b/crates/c-api/include/wasmtime/gc.hh@@ -7,11 +7,14 @@#ifndef WASMTIME_GC_HH#define WASMTIME_GC_HH+#include <vector>#include <wasmtime/gc.h>#include <wasmtime/val.hh>namespace wasmtime {+class StructRef;+/*** \brief Representation of a WebAssembly `eqref` value.*@@ -87,14 +90,198 @@ public:return std::nullopt;}+ /// Returns `true` if this eqref is a structref.+ bool is_struct(Store::Context cx) const {+ return wasmtime_eqref_is_struct(cx.capi(), &val);+ }+/// Upcast this `eqref` to an `anyref`.AnyRef to_anyref() const {wasmtime_anyref_t out;wasmtime_eqref_to_anyref(&val, &out);return AnyRef(out);}++ /// Downcast this `eqref` into a `structref`.+ //+ // as_struct() defined after StructRef below.+ inline StructRef as_struct(Store::Context cx) const;+};++/**+ * \brief Describes the storage type and mutability of a struct field or array+ * element.+ */+struct FieldType {+ /// The field's storage kind.+ wasmtime_storage_kind_t kind;+ /// Whether the field is mutable or not.+ bool mutable_;++ /// Create a mutable field type.+ static FieldType mut_(wasmtime_storage_kind_t k) { return {k, true}; }+ /// Create an immutable field type.+ static FieldType const_(wasmtime_storage_kind_t k) { return {k, false}; }+};++/**+ * \brief Owned handle to a WebAssembly struct type definition.+ *+ * Create with StructType::create, then use with StructRefPre to allocate+ * instances.+ */+class StructType {+ struct Deleter {+ void operator()(wasmtime_struct_type_t *p) const {+ wasmtime_struct_type_delete(p);+ }+ };+ std::unique_ptr<wasmtime_struct_type_t, Deleter> ptr;++public:+ /// Create a new struct type with the given fields.+ static StructType create(const Engine &engine,+ const std::vector<FieldType> &fields) {+ static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));+ auto *raw = wasmtime_struct_type_new(+ engine.capi(),+ reinterpret_cast<const wasmtime_field_type_t *>(fields.data()),+ fields.size());+ StructType ty;+ ty.ptr.reset(raw);+ return ty;+ }++ /// Get the underlying C pointer (non-owning).+ const wasmtime_struct_type_t *capi() const { return ptr.get(); }++private:+ StructType() = default;+ friend class StructRefPre;};+/**+ * \brief Pre-allocated struct layout for fast allocation of struct instances.+ *+ * Created from a StructType and a store context. Reusable for allocating+ * many struct instances of the same type.+ */+class StructRefPre {+ friend class StructRef;+ WASMTIME_OWN_WRAPPER(StructRefPre, wasmtime_struct_ref_pre)++public:+ /// Create a new struct pre-allocator.+ static StructRefPre create(Store::Context cx, const StructType &ty) {+ auto *raw = wasmtime_struct_ref_pre_new(cx.capi(), ty.capi());+ StructRefPre pre(raw);+ return pre;+ }+};++/**+ * \brief Representation of a WebAssembly `structref` value.+ *+ * A `structref` is a reference to a GC struct instance. It is a subtype+ * of `eqref` and `anyref`.+ */+class StructRef {+ friend class EqRef;+ friend class Val;+ friend class AnyRef;++ wasmtime_structref_t val;++public:+ /// Create a `StructRef` from its C-API representation.+ explicit StructRef(wasmtime_structref_t val) : val(val) {}++ /// Clone a `StructRef`.+ StructRef(const StructRef &other) {+ wasmtime_structref_clone(&other.val, &val);+ }++ /// Clone a `StructRef` into this one.+ StructRef &operator=(const StructRef &other) {+ wasmtime_structref_unroot(&val);+ wasmtime_structref_clone(&other.val, &val);+ return *this;+ }++ /// Move a `StructRef`.+ StructRef(StructRef &&other) {+ val = other.val;+ wasmtime_structref_set_null(&other.val);+ }++ /// Move a `StructRef` into this one.+ StructRef &operator=(StructRef &&other) {+ wasmtime_structref_unroot(&val);+ val = other.val;+ wasmtime_structref_set_null(&other.val);+ return *this;+ }++ /// Unroot this `StructRef`.+ ~StructRef() { wasmtime_structref_unroot(&val); }++ /// Allocate a new struct instance.+ static Result<StructRef> create(Store::Context cx, const StructRefPre &pre,+ const std::vector<Val> &fields) {+ std::vector<wasmtime_val_t> c_fields;+ c_fields.reserve(fields.size());+ for (auto &f : fields) {+ c_fields.push_back(f.val);+ }++ wasmtime_structref_t out;+ auto *err = wasmtime_structref_new(cx.capi(), pre.capi(), c_fields.data(),+ c_fields.size(), &out);+ if (err)+ return Result<StructRef>(Error(err));+ return Result<StructRef>(StructRef(out));+ }++ /// Read a field from the struct.+ Result<Val> field(Store::Context cx, size_t index) const {+ wasmtime_val_t out;+ auto *err = wasmtime_structref_field(cx.capi(), &val, index, &out);+ if (err)+ return Result<Val>(Error(err));+ return Result<Val>(Val(out));+ }++ /// Set a field of the struct.+ Result<std::monostate> set_field(Store::Context cx, size_t index,+ const Val &value) const {+ auto *err =+ wasmtime_structref_set_field(cx.capi(), &val, index, &value.val);+ if (err)+ return Result<std::monostate>(Error(err));+ return Result<std::monostate>(std::monostate{});+ }++ /// Upcast to anyref.+ AnyRef to_anyref() const {+ wasmtime_anyref_t out;+ wasmtime_structref_to_anyref(&val, &out);+ return AnyRef(out);+ }++ /// Upcast to eqref.+ EqRef to_eqref() const {+ wasmtime_eqref_t out;+ wasmtime_structref_to_eqref(&val, &out);+ return EqRef(out);+ }+};++inline StructRef EqRef::as_struct(Store::Context cx) const {+ wasmtime_structref_t out;+ wasmtime_eqref_as_struct(cx.capi(), &val, &out);+ return StructRef(out);+}+} // namespace wasmtime#endif // WASMTIME_GC_HHdiff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hhindex b93e10af5e..4885e9702f 100644--- a/crates/c-api/include/wasmtime/val.hh+++ b/crates/c-api/include/wasmtime/val.hh@@ -214,6 +214,7 @@ class Val {friend class Table;friend class Func;friend class Exn;+ friend class StructRef;wasmtime_val_t val;diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rsindex d72631b462..17e494b624 100644--- a/crates/c-api/src/ref.rs+++ b/crates/c-api/src/ref.rs@@ -1,7 +1,10 @@use crate::{WasmtimeStoreContextMut, abort};use std::mem::{ManuallyDrop, MaybeUninit};use std::{num::NonZeroU64, os::raw::c_void, ptr};-use wasmtime::{AnyRef, EqRef, ExnRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};+use wasmtime::{+ AnyRef, EqRef, ExnRef, ExternRef, FieldType, I31, Mutability, OwnedRooted, Ref, RootScope,+ StorageType, StructRef, StructRefPre, StructType, Val, ValType,+};/// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by/// the C API. Because we do not have a uniform representation for `funcref`s@@ -265,8 +268,20 @@ macro_rules! ref_wrapper {ref_wrapper!(AnyRef => wasmtime_anyref_t);ref_wrapper!(ExternRef => wasmtime_externref_t);ref_wrapper!(EqRef => wasmtime_eqref_t);+ref_wrapper!(StructRef => wasmtime_structref_t);ref_wrapper!(ExnRef => wasmtime_exnref_t);+// Opaque types for struct type and struct ref pre-allocator+pub struct wasmtime_struct_type_t {+ ty: StructType,+}+wasmtime_c_api_macros::declare_own!(wasmtime_struct_type_t);++pub struct wasmtime_struct_ref_pre_t {+ pre: StructRefPre,+}+wasmtime_c_api_macros::declare_own!(wasmtime_struct_ref_pre_t);+#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_anyref_clone(anyref: Option<&wasmtime_anyref_t>,@@ -540,3 +555,202 @@ pub unsafe extern "C" fn wasmtime_eqref_i31_get_s(}false}++pub type wasmtime_storage_kind_t = u8;+pub const WASMTIME_STORAGE_KIND_I8: wasmtime_storage_kind_t = 9;+pub const WASMTIME_STORAGE_KIND_I16: wasmtime_storage_kind_t = 10;++#[repr(C)]+pub struct wasmtime_field_type_t {+ pub kind: wasmtime_storage_kind_t,+ pub mutable_: bool,+}++fn field_type_from_c(ft: &wasmtime_field_type_t) -> FieldType {+ let mutability = if ft.mutable_ {+ Mutability::Var+ } else {+ Mutability::Const+ };+ let storage = match ft.kind {+ WASMTIME_STORAGE_KIND_I8 => StorageType::I8,+ WASMTIME_STORAGE_KIND_I16 => StorageType::I16,+ crate::WASMTIME_I32 => StorageType::ValType(ValType::I32),+ crate::WASMTIME_I64 => StorageType::ValType(ValType::I64),+ crate::WASMTIME_F32 => StorageType::ValType(ValType::F32),+ crate::WASMTIME_F64 => StorageType::ValType(ValType::F64),+ crate::WASMTIME_V128 => StorageType::ValType(ValType::V128),+ crate::WASMTIME_FUNCREF => StorageType::ValType(ValType::FUNCREF),+ crate::WASMTIME_EXTERNREF => StorageType::ValType(ValType::EXTERNREF),+ crate::WASMTIME_ANYREF => StorageType::ValType(ValType::ANYREF),+ crate::WASMTIME_EXNREF => StorageType::ValType(ValType::EXNREF),+ other => panic!("unknown wasmtime_storage_kind_t: {other}"),+ };+ FieldType::new(mutability, storage)+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_struct_type_new(+ engine: &crate::wasm_engine_t,+ fields: *const wasmtime_field_type_t,+ nfields: usize,+) -> Box<wasmtime_struct_type_t> {+ let fields = if nfields == 0 {+ &[]+ } else {+ unsafe { std::slice::from_raw_parts(fields, nfields) }+ };+ let field_types: Vec<FieldType> = fields.iter().map(field_type_from_c).collect();+ let ty = StructType::new(&engine.engine, field_types).expect("failed to create struct type");+ Box::new(wasmtime_struct_type_t { ty })+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_struct_ref_pre_new(+ cx: WasmtimeStoreContextMut<'_>,+ ty: &wasmtime_struct_type_t,+) -> Box<wasmtime_struct_ref_pre_t> {+ let pre = StructRefPre::new(cx, ty.ty.clone());+ Box::new(wasmtime_struct_ref_pre_t { pre })+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_new(+ mut cx: WasmtimeStoreContextMut<'_>,+ pre: &wasmtime_struct_ref_pre_t,+ fields: *const crate::wasmtime_val_t,+ nfields: usize,+ out: &mut MaybeUninit<wasmtime_structref_t>,+) -> Option<Box<crate::wasmtime_error_t>> {+ let c_fields = if nfields == 0 {+ &[]+ } else {+ std::slice::from_raw_parts(fields, nfields)+ };+ let mut scope = RootScope::new(&mut cx);+ let vals: Vec<Val> = c_fields.iter().map(|v| v.to_val(&mut scope)).collect();+ match StructRef::new(&mut scope, &pre.pre, &vals) {+ Ok(structref) => {+ let owned = structref+ .to_owned_rooted(&mut scope)+ .expect("just allocated");+ crate::initialize(out, Some(owned).into());+ None+ }+ Err(e) => {+ crate::initialize(out, None::<OwnedRooted<StructRef>>.into());+ Some(Box::new(e.into()))+ }+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_clone(+ structref: Option<&wasmtime_structref_t>,+ out: &mut MaybeUninit<wasmtime_structref_t>,+) {+ let structref = structref.and_then(|s| s.as_wasmtime());+ crate::initialize(out, structref.into());+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_unroot(+ structref: Option<&mut ManuallyDrop<wasmtime_structref_t>>,+) {+ if let Some(structref) = structref {+ ManuallyDrop::drop(structref);+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_to_anyref(+ structref: Option<&wasmtime_structref_t>,+ out: &mut MaybeUninit<wasmtime_anyref_t>,+) {+ let anyref = structref+ .and_then(|s| s.as_wasmtime())+ .map(|s| s.to_anyref());+ crate::initialize(out, anyref.into());+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_to_eqref(+ structref: Option<&wasmtime_structref_t>,+ out: &mut MaybeUninit<wasmtime_eqref_t>,+) {+ let eqref = structref+ .and_then(|s| s.as_wasmtime())+ .map(|s| s.to_eqref());+ crate::initialize(out, eqref.into());+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_field(+ mut cx: WasmtimeStoreContextMut<'_>,+ structref: Option<&wasmtime_structref_t>,+ index: usize,+ out: &mut MaybeUninit<crate::wasmtime_val_t>,+) -> Option<Box<crate::wasmtime_error_t>> {+ let structref = structref+ .and_then(|s| s.as_wasmtime())+ .expect("non-null structref required");+ let mut scope = RootScope::new(&mut cx);+ let rooted = structref.to_rooted(&mut scope);+ match rooted.field(&mut scope, index) {+ Ok(val) => {+ let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);+ crate::initialize(out, c_val);+ None+ }+ Err(e) => Some(Box::new(e.into())),+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_structref_set_field(+ mut cx: WasmtimeStoreContextMut<'_>,+ structref: Option<&wasmtime_structref_t>,+ index: usize,+ val: &crate::wasmtime_val_t,+) -> Option<Box<crate::wasmtime_error_t>> {+ let structref = structref+ .and_then(|s| s.as_wasmtime())+ .expect("non-null structref required");+ let mut scope = RootScope::new(&mut cx);+ let rooted = structref.to_rooted(&mut scope);+ let rust_val = val.to_val(&mut scope);+ match rooted.set_field(&mut scope, index, rust_val) {+ Ok(()) => None,+ Err(e) => Some(Box::new(e.into())),+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_is_struct(+ cx: WasmtimeStoreContextMut<'_>,+ eqref: Option<&wasmtime_eqref_t>,+) -> bool {+ match eqref.and_then(|e| e.as_wasmtime()) {+ Some(eqref) => eqref.is_struct(&cx).expect("OwnedRooted always in scope"),+ None => false,+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_as_struct(+ mut cx: WasmtimeStoreContextMut<'_>,+ eqref: Option<&wasmtime_eqref_t>,+ out: &mut MaybeUninit<wasmtime_structref_t>,+) -> bool {+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {+ let mut scope = RootScope::new(&mut cx);+ let rooted = eqref.to_rooted(&mut scope);+ if let Ok(Some(structref)) = rooted.as_struct(&scope) {+ let owned = structref.to_owned_rooted(&mut scope).expect("in scope");+ crate::initialize(out, Some(owned).into());+ return true;+ }+ }+ crate::initialize(out, None::<OwnedRooted<StructRef>>.into());+ false+}diff --git a/crates/c-api/tests/gc.cc b/crates/c-api/tests/gc.ccindex aa5b4233ee..896f68c757 100644--- a/crates/c-api/tests/gc.cc+++ b/crates/c-api/tests/gc.cc@@ -90,3 +90,73 @@ TEST(I31Ref, SignedValues) {ASSERT_TRUE(s.has_value());EXPECT_EQ(*s, -1);}++TEST(StructRef, CreateAndReadFields) {+ Config config;+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);+ auto cx = store.context();++ // Create a struct type with two mutable i32 fields.+ auto ty = StructType::create(engine, {+ FieldType::mut_(WASMTIME_I32),+ FieldType::mut_(WASMTIME_I32),+ });+ auto pre = StructRefPre::create(cx, ty);++ // Allocate a struct with field values 10 and 20.+ auto result =+ StructRef::create(cx, pre, {Val(int32_t(10)), Val(int32_t(20))});+ ASSERT_TRUE(result);+ StructRef s = result.ok();++ // Read fields back.+ auto v0 = s.field(cx, 0);+ ASSERT_TRUE(v0);+ EXPECT_EQ(v0.ok().i32(), 10);++ auto v1 = s.field(cx, 1);+ ASSERT_TRUE(v1);+ EXPECT_EQ(v1.ok().i32(), 20);++ // Write field 0 to 42 and read back.+ auto set_result = s.set_field(cx, 0, Val(int32_t(42)));+ ASSERT_TRUE(set_result);++ auto v0b = s.field(cx, 0);+ ASSERT_TRUE(v0b);+ EXPECT_EQ(v0b.ok().i32(), 42);+}++TEST(StructRef, UpcastAndDowncast) {+ Config config;+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);+ auto cx = store.context();++ auto ty = StructType::create(engine, {+ FieldType::const_(WASMTIME_I32),+ });+ auto pre = StructRefPre::create(cx, ty);++ auto result = StructRef::create(cx, pre, {Val(int32_t(99))});+ ASSERT_TRUE(result);+ StructRef s = result.ok();++ // Upcast to eqref.+ EqRef eq = s.to_eqref();+ EXPECT_TRUE(eq.is_struct(cx));+ EXPECT_FALSE(eq.is_i31(cx));++ // Downcast back to structref.+ StructRef s2 = eq.as_struct(cx);+ auto v = s2.field(cx, 0);+ ASSERT_TRUE(v);+ EXPECT_EQ(v.ok().i32(), 99);++ // Upcast to anyref.+ AnyRef any = s.to_anyref();+ EXPECT_FALSE(any.is_i31(cx));+}