summaryrefslogtreecommitdiff
path: root/crates/parser
diff options
context:
space:
mode:
authorHenry Gressmann <mail@henrygressmann.de>2026-08-23 13:40:38 +0200
committerGitHub <noreply@github.com>2026-08-23 13:40:38 +0200
commit951c8070169e8bd970940029156f305e741aecdb (patch)
treefbf012a24cbd380b689958122e7f66a2a85d23e1 /crates/parser
parent358a183e5c12c32b8836acf9c71799f56e00b036 (diff)
chore: remove LinearMemory trait (#53)
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/parser')
-rw-r--r--crates/parser/src/conversion.rs19
-rw-r--r--crates/parser/src/error.rs2
-rw-r--r--crates/parser/src/lib.rs39
-rw-r--r--crates/parser/src/module.rs47
-rw-r--r--crates/parser/src/parallel.rs31
-rw-r--r--crates/parser/src/visit.rs2
6 files changed, 34 insertions, 106 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index b94ebe6..364bae8 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -151,29 +151,26 @@ pub(crate) fn convert_module_code(
ty_idx: u32,
options: &ParserOptions,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
- let locals_reader = func.get_locals_reader()?;
- #[cfg(feature = "validate")]
- let locals_position = locals_reader.original_position();
+ let mut locals_reader = func.get_locals_reader()?;
let signature = metadata.signature(ty_idx)?.clone();
let mut local_types = signature.params.clone();
#[cfg(feature = "validate")]
let mut validator = validator;
- #[cfg(feature = "validate")]
- for (local_index, local) in locals_reader.into_iter().enumerate() {
- let local = local?;
+ for _ in 0..locals_reader.get_count() {
+ #[cfg(feature = "validate")]
+ let position = locals_reader.original_position();
+ let local = locals_reader.read()?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
- validator.define_locals(locals_position + local_index, local.0, local.1)?;
+ validator.define_locals(position, local.0, local.1)?;
}
extend_local_types(&mut local_types, local.0, local.1)?;
}
#[cfg(not(feature = "validate"))]
- for local in locals_reader {
- let local = local?;
- extend_local_types(&mut local_types, local.0, local.1)?;
- }
+ let _ = validator;
// maps a local's address to the index in the type's locals array
let mut local_addr_map = Vec::with_capacity(local_types.len());
diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs
index e4d8abd..892e27b 100644
--- a/crates/parser/src/error.rs
+++ b/crates/parser/src/error.rs
@@ -20,7 +20,7 @@ pub enum ParseError {
/// The error message
message: String,
/// The offset in the module where the error occurred
- offset: usize,
+ offset: u64,
},
/// An invalid encoding was encountered
InvalidEncoding(Encoding),
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index 90e239b..262cc07 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -61,8 +61,6 @@ pub struct ParserOptions {
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub validation: bool,
- /// Whether to optimize local memory allocation by skipping allocation of unused local memories.
- pub optimize_local_memory_allocation: bool,
/// Whether to run the peephole rewrite optimizer.
pub optimize_rewrite: bool,
/// Whether to deduplicate immutable function operands while parsing.
@@ -85,7 +83,6 @@ impl Default for ParserOptions {
fn default() -> Self {
Self {
validation: cfg!(feature = "validate"),
- optimize_local_memory_allocation: true,
optimize_rewrite: true,
deduplicate_operands: false,
#[cfg(parallel_parser)]
@@ -117,17 +114,6 @@ impl ParserOptions {
self.validation
}
- /// Enable or disable the optimization that skips allocating unused local memories.
- pub const fn with_local_memory_allocation_optimization(mut self, enabled: bool) -> Self {
- self.optimize_local_memory_allocation = enabled;
- self
- }
-
- /// Returns whether unused local memory allocation optimization is enabled.
- pub const fn optimize_local_memory_allocation(&self) -> bool {
- self.optimize_local_memory_allocation
- }
-
/// Enable or disable the peephole rewrite optimizer.
pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self {
self.optimize_rewrite = enabled;
@@ -234,7 +220,7 @@ impl Parser {
}
reader.process_pending_functions(&self.options)?;
- reader.into_module(&self.options)
+ reader.into_module()
}
#[cfg(feature = "std")]
@@ -263,7 +249,7 @@ impl Parser {
buffer.truncate(buffer.len() - buffer_offset);
buffer_offset = 0;
}
- let read_bytes = Self::read_more(&mut stream, &mut buffer, hint as usize)?;
+ let read_bytes = Self::read_more(&mut stream, &mut buffer, hint)?;
eof = read_bytes == 0;
}
wasmparser::Chunk::Parsed { consumed, payload } => {
@@ -272,17 +258,12 @@ impl Parser {
match payload {
wasmparser::Payload::CodeSectionStart { count, range, size } => {
- let defer = reader.begin_code_section(
- count,
- range.clone(),
- size,
- validator.as_mut(),
- &self.options,
- )?;
+ let defer =
+ reader.begin_code_section(count, range, size, validator.as_mut(), &self.options)?;
#[cfg(parallel_parser)]
if defer {
- deferred_code_section = Some((count, range.end - size as usize, size as usize));
+ deferred_code_section = Some((count, size as usize));
}
#[cfg(not(parallel_parser))]
@@ -298,21 +279,21 @@ impl Parser {
buffer_offset += consumed;
#[cfg(parallel_parser)]
- if let Some((count, body_offset, section_size)) = deferred_code_section {
+ if let Some((count, section_size)) = deferred_code_section {
while buffer.len() - buffer_offset < section_size {
let remaining = section_size - (buffer.len() - buffer_offset);
let read_bytes = Self::read_more(&mut stream, &mut buffer, remaining)?;
if read_bytes == 0 {
return Err(ParseError::ParseError {
message: "unexpected end-of-file".into(),
- offset: body_offset + buffer.len() - buffer_offset,
+ offset: parser.offset() + (buffer.len() - buffer_offset) as u64,
});
}
}
let section_end = buffer_offset + section_size;
let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
- reader.queue_owned_code_section(count, body_offset, section_bytes, validator.as_mut())?;
+ reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?;
parser.skip_section();
buffer_offset = section_end;
continue;
@@ -335,7 +316,7 @@ impl Parser {
if reader.end_reached || eof {
reader.process_pending_functions(&self.options)?;
- return reader.into_module(&self.options);
+ return reader.into_module();
}
}
};
@@ -347,7 +328,7 @@ impl TryFrom<ModuleReader<'_>> for Module {
type Error = ParseError;
fn try_from(reader: ModuleReader<'_>) -> Result<Self> {
- reader.into_module(&ParserOptions::default())
+ reader.into_module()
}
}
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index 8138666..c076035 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -19,7 +19,6 @@ pub(crate) struct OptimizedFunctionCode {
pub instructions: Vec<Instruction>,
pub data: WasmFunctionData,
pub locals: ValueCounts,
- pub uses_local_memory: bool,
}
pub(crate) fn optimize_function_code(
@@ -27,16 +26,11 @@ pub(crate) fn optimize_function_code(
options: &ParserOptions,
function_results: ValueCounts,
self_func_addr: u32,
- imported_memory_count: u32,
) -> Result<OptimizedFunctionCode> {
let optimized =
optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?;
let data = code.data.finish();
- let uses_local_memory = optimized
- .instructions
- .iter()
- .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count));
- Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory })
+ Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals })
}
#[derive(Default)]
@@ -65,7 +59,6 @@ pub(crate) struct ModuleReader<'a> {
pub(crate) elements: Box<[Element]>,
pub(crate) end_reached: bool,
imported_func_count: usize,
- imported_memory_count: u32,
global_types: Vec<WasmType>,
#[cfg(parallel_parser)]
@@ -277,7 +270,6 @@ impl<'a> ModuleReader<'a> {
}
self.imported_func_count += 1;
}
- ImportKind::Memory(_) => self.imported_memory_count += 1,
ImportKind::Global(ty) => self.global_types.push(ty.ty),
ImportKind::Tag(tag) => {
let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| {
@@ -338,7 +330,7 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn begin_code_section(
&mut self,
count: u32,
- range: Range<usize>,
+ range: Range<u64>,
size: u32,
validator: Option<&mut Validator>,
options: &ParserOptions,
@@ -411,7 +403,6 @@ impl<'a> ModuleReader<'a> {
options,
self.code_results[self.code.len()],
(self.imported_func_count + self.code.len()) as u32,
- self.imported_memory_count,
)?);
self.func_validator_allocations = func_validator_allocs;
@@ -443,7 +434,7 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn queue_owned_code_section(
&mut self,
count: u32,
- body_offset: usize,
+ body_offset: u64,
section_bytes: Arc<[u8]>,
validator: Option<&mut Validator>,
) -> Result<()> {
@@ -455,6 +446,8 @@ impl<'a> ModuleReader<'a> {
for _ in 0..count {
let body_reader = reader.read_reader()?;
let body_range = body_reader.range();
+ let body_start = (body_range.start - body_offset) as usize;
+ let body_end = (body_range.end - body_offset) as usize;
#[cfg(feature = "validate")]
let func_to_validate = {
let function = wasmparser::FunctionBody::new(body_reader);
@@ -465,7 +458,7 @@ impl<'a> ModuleReader<'a> {
self.queue_function(
crate::parallel::FunctionBodyInput::Owned(crate::parallel::OwnedFunctionBody {
section_bytes: section_bytes.clone(),
- body_range: (body_range.start - body_offset)..(body_range.end - body_offset),
+ body_range: body_start..body_end,
body_offset: body_range.start,
}),
func_to_validate,
@@ -512,10 +505,8 @@ impl<'a> ModuleReader<'a> {
};
let imported_func_count = self.imported_func_count;
- let imported_memory_count = self.imported_memory_count;
let metadata = self.translation_metadata();
- let code =
- crate::parallel::process_pending(pending, metadata, options, imported_func_count, imported_memory_count)?;
+ let code = crate::parallel::process_pending(pending, metadata, options, imported_func_count)?;
self.code.extend(code);
Ok(())
}
@@ -525,7 +516,7 @@ impl<'a> ModuleReader<'a> {
Ok(())
}
- pub(crate) fn into_module(self, options: &ParserOptions) -> Result<Module> {
+ pub(crate) fn into_module(self) -> Result<Module> {
if !self.end_reached {
return Err(ParseError::EndNotReached);
}
@@ -534,24 +525,6 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::Other("Code and code type address count mismatch".to_string()));
}
- let import_mem_count = self.imported_memory_count;
- let has_local_mem_export =
- self.exports.iter().any(|export| export.kind == ExternalKind::Memory && export.index >= import_mem_count);
- let has_active_data_segment_on_local_memory = self.data.iter().any(|data| match &data.kind {
- DataKind::Active { mem, .. } => *mem >= import_mem_count,
- DataKind::Passive => false,
- });
- let optimize_local_memory_allocation = options.optimize_local_memory_allocation();
- let mut local_memory_allocation = if self.memory_types.is_empty() {
- LocalMemoryAllocation::Skip
- } else if !optimize_local_memory_allocation || has_active_data_segment_on_local_memory {
- LocalMemoryAllocation::Eager
- } else if has_local_mem_export {
- LocalMemoryAllocation::Lazy
- } else {
- LocalMemoryAllocation::Skip
- };
-
let func_type_idxs = self
.imports
.iter()
@@ -571,9 +544,6 @@ impl<'a> ModuleReader<'a> {
let ty =
self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing");
let params = ValueCounts::from_iter(ty.params());
- if code.uses_local_memory {
- local_memory_allocation = LocalMemoryAllocation::Eager;
- }
Ok(Arc::new(WasmFunction {
instructions: code.instructions.into_boxed_slice(),
@@ -598,7 +568,6 @@ impl<'a> ModuleReader<'a> {
elements: self.elements,
memory_types: self.memory_types,
tags: self.tags,
- local_memory_allocation,
}
.into())
}
diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs
index e29b38f..9b96c7a 100644
--- a/crates/parser/src/parallel.rs
+++ b/crates/parser/src/parallel.rs
@@ -17,7 +17,7 @@ pub(crate) struct OwnedFunctionBody {
// function jobs from that section.
pub section_bytes: Arc<[u8]>,
pub body_range: Range<usize>,
- pub body_offset: usize,
+ pub body_offset: u64,
}
pub(crate) struct PendingFunction<'a> {
@@ -61,7 +61,6 @@ fn process_function_job(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
validator_allocs: Option<FuncValidatorAllocations>,
reader_allocs: OperatorsReaderAllocations,
) -> Result<(OptimizedFunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
@@ -83,13 +82,7 @@ fn process_function_job(
}
};
- let code = optimize_function_code(
- code,
- options,
- job.results,
- (imported_func_count + job.ordinal) as u32,
- imported_memory_count,
- )?;
+ let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?;
Ok((code, validator_allocs, reader_allocs))
}
@@ -99,7 +92,6 @@ fn process_chunk<'a>(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<OptimizedFunctionCode>> {
let mut validator_allocs = None;
let mut reader_allocs = OperatorsReaderAllocations::default();
@@ -107,15 +99,8 @@ fn process_chunk<'a>(
let mut codes = Vec::with_capacity(jobs.size_hint().0);
for job in jobs {
- let (code, next_validator_allocs, next_reader_allocs) = process_function_job(
- job,
- metadata,
- options,
- imported_func_count,
- imported_memory_count,
- validator_allocs,
- reader_allocs,
- )?;
+ let (code, next_validator_allocs, next_reader_allocs) =
+ process_function_job(job, metadata, options, imported_func_count, validator_allocs, reader_allocs)?;
codes.push(code);
validator_allocs = next_validator_allocs;
reader_allocs = next_reader_allocs;
@@ -129,11 +114,10 @@ pub(crate) fn process_pending(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<OptimizedFunctionCode>> {
let num_workers = worker_count(options, pending.len());
if num_workers == 1 {
- return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count);
+ return process_chunk(pending, metadata, options, imported_func_count);
}
let code_count = pending.len();
let chunk_size = pending.len().div_ceil(num_workers);
@@ -151,10 +135,7 @@ pub(crate) fn process_pending(
bytes += body_len(&job.body);
chunk.push(job);
}
- handles
- .push(scope.spawn(move || {
- process_chunk(chunk, metadata, options, imported_func_count, imported_memory_count)
- }));
+ handles.push(scope.spawn(move || process_chunk(chunk, metadata, options, imported_func_count)));
}
let mut codes = Vec::with_capacity(code_count);
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index 8315fb5..f48e1cf 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -221,7 +221,7 @@ impl<'a> FunctionBuilder<'a> {
struct ValidateThenVisit<'a, 'm> {
validator: &'a mut FuncValidator<ValidatorResources>,
builder: &'a mut FunctionBuilder<'m>,
- position: usize,
+ position: u64,
}
impl ModuleMetadata {