summaryrefslogtreecommitdiff
path: root/crates/parser/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/parser/src')
-rw-r--r--crates/parser/src/conversion.rs13
-rw-r--r--crates/parser/src/error.rs26
-rw-r--r--crates/parser/src/lib.rs13
-rw-r--r--crates/parser/src/module.rs66
-rw-r--r--crates/parser/src/std.rs2
5 files changed, 60 insertions, 60 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index 7c10d62..38a2ada 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -131,7 +131,7 @@ pub(crate) fn convert_module_globals<'a, T: IntoIterator<Item = wasmparser::Resu
Ok(globals)
}
-pub(crate) fn convert_module_export(export: wasmparser::Export) -> Result<Export> {
+pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Export> {
let kind = match export.kind {
wasmparser::ExternalKind::Func => ExternalKind::Func,
wasmparser::ExternalKind::Table => ExternalKind::Table,
@@ -146,7 +146,7 @@ pub(crate) fn convert_module_export(export: wasmparser::Export) -> Result<Export
}
pub(crate) fn convert_module_code(
- func: wasmparser::FunctionBody,
+ func: wasmparser::FunctionBody<'_>,
mut validator: FuncValidator<ValidatorResources>,
) -> Result<CodeSection> {
let locals_reader = func.get_locals_reader()?;
@@ -205,18 +205,17 @@ pub(crate) fn convert_memarg(memarg: wasmparser::MemArg) -> MemoryArg {
MemoryArg { offset: memarg.offset, align: memarg.align, align_max: memarg.max_align, mem_addr: memarg.memory }
}
-pub(crate) fn process_const_operators(ops: OperatorsReader) -> Result<ConstInstruction> {
+pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<ConstInstruction> {
let ops = ops.into_iter().collect::<wasmparser::Result<Vec<_>>>()?;
// In practice, the len can never be something other than 2,
// but we'll keep this here since it's part of the spec
// Invalid modules will be rejected by the validator anyway (there are also tests for this in the testsuite)
assert!(ops.len() >= 2);
assert!(matches!(ops[ops.len() - 1], wasmparser::Operator::End));
-
process_const_operator(ops[ops.len() - 2].clone())
}
-pub fn process_const_operator(op: wasmparser::Operator) -> Result<ConstInstruction> {
+pub(crate) fn process_const_operator(op: wasmparser::Operator<'_>) -> Result<ConstInstruction> {
match op {
wasmparser::Operator::RefNull { ty } => Ok(ConstInstruction::RefNull(convert_valtype(&ty))),
wasmparser::Operator::RefFunc { function_index } => Ok(ConstInstruction::RefFunc(function_index)),
@@ -229,7 +228,7 @@ pub fn process_const_operator(op: wasmparser::Operator) -> Result<ConstInstructi
}
}
-pub fn process_operators<'a>(
+pub(crate) fn process_operators<'a>(
mut offset: usize,
ops: impl Iterator<Item = Result<wasmparser::Operator<'a>, wasmparser::BinaryReaderError>>,
mut validator: FuncValidator<ValidatorResources>,
@@ -515,7 +514,6 @@ pub fn process_operators<'a>(
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported instruction: {:?}", op)));
}
};
-
instructions.push(res);
}
@@ -524,6 +522,5 @@ pub fn process_operators<'a>(
}
validator.finish(offset)?;
-
Ok(instructions.into_boxed_slice())
}
diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs
index 35bad28..76d806d 100644
--- a/crates/parser/src/error.rs
+++ b/crates/parser/src/error.rs
@@ -6,15 +6,35 @@ use wasmparser::Encoding;
#[derive(Debug)]
/// Errors that can occur when parsing a WebAssembly module
pub enum ParseError {
+ /// An invalid type was encountered
InvalidType,
+ /// An unsupported section was encountered
UnsupportedSection(String),
+ /// A duplicate section was encountered
DuplicateSection(String),
+ /// An empty section was encountered
EmptySection(String),
+ /// An unsupported operator was encountered
UnsupportedOperator(String),
- ParseError { message: String, offset: usize },
+ /// An error occurred while parsing the module
+ ParseError {
+ /// The error message
+ message: String,
+ /// The offset in the module where the error occurred
+ offset: usize,
+ },
+ /// An invalid encoding was encountered
InvalidEncoding(Encoding),
- InvalidLocalCount { expected: u32, actual: u32 },
+ /// An invalid local count was encountered
+ InvalidLocalCount {
+ /// The expected local count
+ expected: u32,
+ /// The actual local count
+ actual: u32,
+ },
+ /// The end of the module was not reached
EndNotReached,
+ /// An unknown error occurred
Other(String),
}
@@ -48,4 +68,4 @@ impl From<wasmparser::BinaryReaderError> for ParseError {
}
}
-pub type Result<T, E = ParseError> = core::result::Result<T, E>;
+pub(crate) type Result<T, E = ParseError> = core::result::Result<T, E>;
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index c608232..8cc34db 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -1,6 +1,12 @@
#![no_std]
+#![doc(test(
+ no_crate_inject,
+ attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_assignments, unused_variables))
+))]
+#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)]
#![forbid(unsafe_code)]
#![cfg_attr(not(feature = "std"), feature(error_in_core))]
+//! See [`tinywasm`](https://docs.rs/tinywasm) for documentation.
mod std;
extern crate alloc;
@@ -30,14 +36,17 @@ use wasmparser::Validator;
pub use tinywasm_types::TinyWasmModule;
-#[derive(Default)]
+/// A WebAssembly parser
+#[derive(Default, Debug)]
pub struct Parser {}
impl Parser {
+ /// Create a new parser instance
pub fn new() -> Self {
Self {}
}
+ /// Parse a [`TinyWasmModule`] from bytes
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<TinyWasmModule> {
let wasm = wasm.as_ref();
let mut validator = Validator::new();
@@ -55,6 +64,7 @@ impl Parser {
}
#[cfg(feature = "std")]
+ /// Parse a [`TinyWasmModule`] from a file. Requires `std` feature.
pub fn parse_module_file(&self, path: impl AsRef<crate::std::path::Path> + Clone) -> Result<TinyWasmModule> {
use alloc::format;
let f = crate::std::fs::File::open(path.clone())
@@ -65,6 +75,7 @@ impl Parser {
}
#[cfg(feature = "std")]
+ /// Parse a [`TinyWasmModule`] from a stream. Requires `std` feature.
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<TinyWasmModule> {
use alloc::format;
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index f5c01ac..a18d343 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -6,58 +6,34 @@ use tinywasm_types::{Data, Element, Export, FuncType, Global, Import, Instructio
use wasmparser::{Payload, Validator};
#[derive(Debug, Clone)]
-pub struct CodeSection {
- pub locals: Box<[ValType]>,
- pub body: Box<[Instruction]>,
+pub(crate) struct CodeSection {
+ pub(crate) locals: Box<[ValType]>,
+ pub(crate) body: Box<[Instruction]>,
}
#[derive(Default)]
-pub struct ModuleReader {
- pub version: Option<u16>,
- pub start_func: Option<u32>,
-
- pub func_types: Vec<FuncType>,
-
- // map from local function index to type index
- pub code_type_addrs: Vec<u32>,
-
- pub exports: Vec<Export>,
- pub code: Vec<CodeSection>,
- pub globals: Vec<Global>,
- pub table_types: Vec<TableType>,
- pub memory_types: Vec<MemoryType>,
- pub imports: Vec<Import>,
- pub data: Vec<Data>,
- pub elements: Vec<Element>,
-
- // pub element_section: Option<ElementSectionReader<'a>>,
- pub end_reached: bool,
-}
-
-impl Debug for ModuleReader {
- fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
- f.debug_struct("ModuleReader")
- .field("version", &self.version)
- .field("func_types", &self.func_types)
- .field("func_addrs", &self.code_type_addrs)
- .field("code", &self.code)
- .field("exports", &self.exports)
- .field("globals", &self.globals)
- .field("table_types", &self.table_types)
- .field("memory_types", &self.memory_types)
- .field("import_section", &self.imports)
- // .field("element_section", &self.element_section)
- // .field("data_section", &self.data_section)
- .finish()
- }
+pub(crate) struct ModuleReader {
+ pub(crate) version: Option<u16>,
+ pub(crate) start_func: Option<u32>,
+ pub(crate) func_types: Vec<FuncType>,
+ pub(crate) code_type_addrs: Vec<u32>,
+ pub(crate) exports: Vec<Export>,
+ pub(crate) code: Vec<CodeSection>,
+ pub(crate) globals: Vec<Global>,
+ pub(crate) table_types: Vec<TableType>,
+ pub(crate) memory_types: Vec<MemoryType>,
+ pub(crate) imports: Vec<Import>,
+ pub(crate) data: Vec<Data>,
+ pub(crate) elements: Vec<Element>,
+ pub(crate) end_reached: bool,
}
impl ModuleReader {
- pub fn new() -> ModuleReader {
+ pub(crate) fn new() -> ModuleReader {
Self::default()
}
- pub fn process_payload(&mut self, payload: Payload, validator: &mut Validator) -> Result<()> {
+ pub(crate) fn process_payload(&mut self, payload: Payload<'_>, validator: &mut Validator) -> Result<()> {
use wasmparser::Payload::*;
match payload {
@@ -191,10 +167,6 @@ impl ModuleReader {
debug!("Found custom section");
debug!("Skipping custom section: {:?}", _reader.name());
}
- // TagSection(tag) => {
- // debug!("Found tag section");
- // validator.tag_section(&tag)?;
- // }
UnknownSection { .. } => return Err(ParseError::UnsupportedSection("Unknown section".into())),
section => return Err(ParseError::UnsupportedSection(format!("Unsupported section: {:?}", section))),
};
diff --git a/crates/parser/src/std.rs b/crates/parser/src/std.rs
index 67152be..16a7058 100644
--- a/crates/parser/src/std.rs
+++ b/crates/parser/src/std.rs
@@ -2,4 +2,4 @@
extern crate std;
#[cfg(feature = "std")]
-pub use std::*;
+pub(crate) use std::*;