Skip to content

Commit c3638a8

Browse files
feat: recursive types, refactor state module
Signed-off-by: Henry <mail@henrygressmann.de>
1 parent eb2b172 commit c3638a8

24 files changed

Lines changed: 701 additions & 367 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Added
1111

1212
- Added support for the WebAssembly function-references proposal
13+
- Added support for the WebAssembly garbage-collection proposal
1314
- Added `WasmValue::ty` and `WasmValue::matches_type`
1415
- Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules.
1516

1617
### Changed
1718

18-
- Function types are now stored separately and resolved through `Function::ty(&Store)`.
19+
- Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`.
1920

2021
### Fixed
2122

‎Cargo.lock‎

Lines changed: 12 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/parser/src/conversion.rs‎

Lines changed: 102 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResour
22
#[cfg(feature = "validate")]
33
use crate::visit::process_operators_and_validate;
44
use crate::{Result, module::FunctionCode, visit::process_operators};
5-
use alloc::{boxed::Box, format, string::ToString, vec::Vec};
5+
use alloc::{boxed::Box, format, vec::Vec};
66
use tinywasm_types::*;
7-
use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations};
7+
use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex};
88

99
pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
1010
let kind = match element.kind {
@@ -208,39 +208,98 @@ pub(crate) fn convert_module_code(
208208
))
209209
}
210210

211-
pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> {
212-
let mut types = ty.types();
213-
// TODO(wasm3): Preserve recursive groups and non-function composite types instead of flattening singleton funcs.
214-
if types.len() != 1 {
215-
return Err(crate::ParseError::UnsupportedOperator(
216-
"Expected exactly one type in the type section".to_string(),
217-
));
211+
pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<SubType>) -> Result<u32> {
212+
let group_len = u32::try_from(ty.types().len())
213+
.map_err(|_| crate::ParseError::Other("recursive type group is too large".into()))?;
214+
types.reserve(group_len as usize);
215+
for ty in ty.into_types() {
216+
let composite = &ty.composite_type;
217+
if composite.shared {
218+
return Err(crate::ParseError::UnsupportedOperator("shared composite types are unsupported".into()));
219+
}
220+
if composite.descriptor_idx.is_some() || composite.describes_idx.is_some() {
221+
return Err(crate::ParseError::UnsupportedOperator("descriptor types are unsupported".into()));
222+
}
223+
224+
let supertype =
225+
ty.supertype_idx.map(|idx| convert_type_index(idx.unpack(), group_start, group_len)).transpose()?;
226+
let composite = match &composite.inner {
227+
CompositeInnerType::Func(ty) => {
228+
let params = ty
229+
.params()
230+
.iter()
231+
.map(|ty| convert_valtype_in_group(ty, group_start, group_len))
232+
.collect::<Result<Vec<_>>>()?;
233+
let results = ty
234+
.results()
235+
.iter()
236+
.map(|ty| convert_valtype_in_group(ty, group_start, group_len))
237+
.collect::<Result<Vec<_>>>()?;
238+
CompositeType::Func(FuncType::new(&params, &results))
239+
}
240+
CompositeInnerType::Struct(ty) => CompositeType::Struct(StructType {
241+
fields: ty
242+
.fields
243+
.iter()
244+
.map(|field| convert_field_type(field, group_start, group_len))
245+
.collect::<Result<_>>()?,
246+
}),
247+
CompositeInnerType::Array(ty) => {
248+
CompositeType::Array(ArrayType { field: convert_field_type(&ty.0, group_start, group_len)? })
249+
}
250+
CompositeInnerType::Cont(_) => {
251+
return Err(crate::ParseError::UnsupportedOperator("continuation types are unsupported".into()));
252+
}
253+
};
254+
types.push(SubType { is_final: ty.is_final, supertype, composite });
255+
}
256+
Ok(group_len)
257+
}
258+
259+
fn convert_type_index(index: UnpackedIndex, group_start: u32, group_len: u32) -> Result<TypeAddr> {
260+
match index {
261+
UnpackedIndex::Module(index) => Ok(index),
262+
UnpackedIndex::RecGroup(index) if index < group_len => {
263+
group_start.checked_add(index).ok_or_else(|| crate::ParseError::Other("type index is too large".into()))
264+
}
265+
UnpackedIndex::RecGroup(index) => {
266+
Err(crate::ParseError::Other(format!("recursive group type index out of bounds: {index}")))
267+
}
268+
_ => Err(crate::ParseError::UnsupportedOperator(format!("unsupported canonical type index: {index}"))),
218269
}
270+
}
219271

220-
let ty = types.next().unwrap();
221-
let CompositeInnerType::Func(ty) = &ty.composite_type.inner else {
222-
return Err(crate::ParseError::UnsupportedOperator(format!(
223-
"Unsupported non-function type in type section: {}",
224-
ty.composite_type
225-
)));
272+
fn convert_field_type(field: &wasmparser::FieldType, group_start: u32, group_len: u32) -> Result<FieldType> {
273+
let storage = match &field.element_type {
274+
wasmparser::StorageType::I8 => StorageType::I8,
275+
wasmparser::StorageType::I16 => StorageType::I16,
276+
wasmparser::StorageType::Val(ty) => StorageType::Value(convert_valtype_in_group(ty, group_start, group_len)?),
226277
};
227-
let params = ty.params().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?;
228-
let results = ty.results().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?;
229-
Ok(FuncType::new(&params, &results))
278+
Ok(FieldType { storage, mutable: field.mutable })
230279
}
231280

232281
pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> {
233282
convert_heap_type(ty.heap_type(), ty.is_nullable())
234283
}
235284

236285
pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> {
286+
convert_valtype_with_group(valtype, None)
287+
}
288+
289+
fn convert_valtype_in_group(valtype: &wasmparser::ValType, group_start: u32, group_len: u32) -> Result<WasmType> {
290+
convert_valtype_with_group(valtype, Some((group_start, group_len)))
291+
}
292+
293+
fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, u32)>) -> Result<WasmType> {
237294
match valtype {
238295
wasmparser::ValType::I32 => Ok(WasmType::I32),
239296
wasmparser::ValType::I64 => Ok(WasmType::I64),
240297
wasmparser::ValType::F32 => Ok(WasmType::F32),
241298
wasmparser::ValType::F64 => Ok(WasmType::F64),
242299
wasmparser::ValType::V128 => Ok(WasmType::V128),
243-
wasmparser::ValType::Ref(r) => Ok(WasmType::Ref(convert_ref_type(*r)?)),
300+
wasmparser::ValType::Ref(r) => {
301+
Ok(WasmType::Ref(convert_heap_type_with_group(r.heap_type(), r.is_nullable(), group)?))
302+
}
244303
}
245304
}
246305

@@ -294,6 +353,14 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
294353
}
295354

296355
pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> Result<RefType> {
356+
convert_heap_type_with_group(heap, nullable, None)
357+
}
358+
359+
fn convert_heap_type_with_group(
360+
heap: wasmparser::HeapType,
361+
nullable: bool,
362+
group: Option<(u32, u32)>,
363+
) -> Result<RefType> {
297364
match heap {
298365
wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract(
299366
nullable,
@@ -316,9 +383,22 @@ pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> R
316383
},
317384
)),
318385
wasmparser::HeapType::Concrete(index) => {
319-
let index = index.as_module_index().ok_or_else(|| {
320-
crate::ParseError::UnsupportedOperator(format!("Unsupported non-module heap type index: {index:?}"))
321-
})?;
386+
let index = match index {
387+
UnpackedIndex::Module(index) => index,
388+
index @ UnpackedIndex::RecGroup(_) => {
389+
let (group_start, group_len) = group.ok_or_else(|| {
390+
crate::ParseError::UnsupportedOperator(format!(
391+
"recursive-group heap type outside a type group: {index}"
392+
))
393+
})?;
394+
convert_type_index(index, group_start, group_len)?
395+
}
396+
index => {
397+
return Err(crate::ParseError::UnsupportedOperator(format!(
398+
"unsupported canonical heap type index: {index}"
399+
)));
400+
}
401+
};
322402
RefType::new_concrete(nullable, index)
323403
.ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}")))
324404
}

‎crates/parser/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ impl Parser {
174174
| WasmFeatures::BULK_MEMORY_OPT
175175
| WasmFeatures::RELAXED_SIMD
176176
| WasmFeatures::GC_TYPES
177+
| WasmFeatures::GC
177178
| WasmFeatures::REFERENCE_TYPES
178179
| WasmFeatures::MUTABLE_GLOBAL
179180
| WasmFeatures::MULTI_VALUE

‎crates/parser/src/module.rs‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,12 @@ pub(crate) struct ModuleReader<'a> {
4444
translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
4545

4646
has_code_section: bool,
47+
has_type_section: bool,
4748
marker: PhantomData<&'a [u8]>,
4849

4950
pub(crate) version: Option<u16>,
5051
pub(crate) start_func: Option<u32>,
51-
pub(crate) func_types: Box<[FuncType]>,
52+
pub(crate) types: TypeSection,
5253
pub(crate) code_type_addrs: Box<[u32]>,
5354
code_results: Box<[ValueCounts]>,
5455
pub(crate) exports: Arc<[Export]>,
@@ -71,7 +72,7 @@ impl<'a> ModuleReader<'a> {
7172
fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata {
7273
if self.translation_metadata.is_none() {
7374
self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new(
74-
&self.func_types,
75+
&self.types,
7576
&self.code_type_addrs,
7677
&self.imports,
7778
&self.globals,
@@ -119,12 +120,25 @@ impl<'a> ModuleReader<'a> {
119120
self.start_func = Some(func);
120121
}
121122
Payload::TypeSection(reader) => {
122-
check_section("type", !self.func_types.is_empty())?;
123+
check_section("type", self.has_type_section)?;
124+
self.has_type_section = true;
123125
#[cfg(feature = "validate")]
124126
if let Some(validator) = validator.as_mut() {
125127
validator.type_section(&reader)?;
126128
}
127-
self.func_types = reader.into_iter().map(|t| convert_module_type(t?)).collect::<Result<_>>()?;
129+
let mut types = Vec::with_capacity(reader.count() as usize);
130+
let mut rec_group_lengths = Vec::with_capacity(reader.count() as usize);
131+
for group in reader {
132+
let group = group?;
133+
let group_start = u32::try_from(types.len())
134+
.map_err(|_| ParseError::Other("type section is too large".into()))?;
135+
let group_len = convert_rec_group(group, group_start, &mut types)?;
136+
rec_group_lengths.push(group_len);
137+
}
138+
self.types = TypeSection {
139+
types: types.into_boxed_slice(),
140+
rec_group_lengths: rec_group_lengths.into_boxed_slice(),
141+
};
128142
}
129143
Payload::GlobalSection(reader) => {
130144
check_section("global", !self.globals.is_empty())?;
@@ -207,10 +221,9 @@ impl<'a> ModuleReader<'a> {
207221
let mut results = Vec::with_capacity(reader.count() as usize);
208222
for ty_idx in reader {
209223
let ty_idx = ty_idx?;
210-
let ty = self
211-
.func_types
212-
.get(ty_idx as usize)
213-
.ok_or_else(|| ParseError::Other(format!("function type index out of bounds: {ty_idx}")))?;
224+
let ty = self.types.get(ty_idx).and_then(SubType::as_func).ok_or_else(|| {
225+
ParseError::Other(format!("function type index does not reference a function: {ty_idx}"))
226+
})?;
214227
type_addrs.push(ty_idx);
215228
results.push(ValueCounts::from_iter(ty.results()));
216229
}
@@ -227,7 +240,14 @@ impl<'a> ModuleReader<'a> {
227240
for import in reader.into_imports() {
228241
let import = convert_module_import(import?)?;
229242
match import.kind {
230-
ImportKind::Function(_) => self.imported_func_count += 1,
243+
ImportKind::Function(type_idx) => {
244+
if self.types.get(type_idx).and_then(SubType::as_func).is_none() {
245+
return Err(ParseError::Other(format!(
246+
"function import type index does not reference a function: {type_idx}"
247+
)));
248+
}
249+
self.imported_func_count += 1;
250+
}
231251
ImportKind::Memory(_) => self.imported_memory_count += 1,
232252
_ => {}
233253
}
@@ -504,7 +524,8 @@ impl<'a> ModuleReader<'a> {
504524
.zip(self.code_type_addrs)
505525
.zip(self.code_results)
506526
.map(|((code, ty_idx), results)| {
507-
let ty = self.func_types.get(ty_idx as usize).expect("function type was checked while parsing").clone();
527+
let ty =
528+
self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing");
508529
let params = ValueCounts::from_iter(ty.params());
509530
if code.uses_local_memory {
510531
local_memory_allocation = LocalMemoryAllocation::Eager;
@@ -522,7 +543,7 @@ impl<'a> ModuleReader<'a> {
522543

523544
Ok(ModuleInner {
524545
funcs,
525-
func_types: self.func_types,
546+
types: self.types,
526547
func_type_idxs,
527548
globals: self.globals,
528549
tables: self.tables,

0 commit comments

Comments
 (0)