Skip to content
This repository was archived by the owner on Oct 3, 2025. It is now read-only.

Commit 5315ea9

Browse files
docs: improve rustdoc
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
1 parent 52bebfa commit 5315ea9

File tree

8 files changed

+121
-61
lines changed

8 files changed

+121
-61
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
- **`std`**\
2020
Enables the use of `std` and `std::io` for parsing from files and streams. This is enabled by default.
2121
- **`logging`**\
22-
Enables logging of the parsing process using the `log` crate. This is enabled by default.
22+
Enables logging using the `log` crate. This is enabled by default.
2323
- **`parser`**\
2424
Enables the `tinywasm-parser` crate. This is enabled by default.
2525

crates/cli/src/args.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::str::FromStr;
2-
use tinywasm::WasmValue;
2+
use tinywasm::types::WasmValue;
33

44
#[derive(Debug)]
55
pub struct WasmArg(WasmValue);

crates/cli/src/bin.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use argh::FromArgs;
44
use args::WasmArg;
55
use color_eyre::eyre::Result;
66
use log::{debug, info};
7-
use tinywasm::{self, Module, WasmValue};
7+
use tinywasm::{self, types::WasmValue, Module};
88

99
use crate::args::to_wasm_args;
1010
mod args;

crates/tinywasm/src/lib.rs

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,56 @@
1010
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)]
1111
#![cfg_attr(feature = "nightly", feature(error_in_core))]
1212

13-
//! ## A tiny WebAssembly Runtime written in Rust
13+
//! A tiny WebAssembly Runtime written in Rust
14+
//!
15+
//! TinyWasm provides a minimal WebAssembly runtime for executing WebAssembly modules.
16+
//! It currently supports a subset of the WebAssembly MVP specification and is intended
17+
//! to be useful for embedded systems and other environments where a full-featured
18+
//! runtime is not required.
19+
//!
20+
//! ## Getting Started
21+
//!
22+
//! The easiest way to get started is to use the [`Module::parse_bytes`] function to load a
23+
//! WebAssembly module from bytes. This will parse the module and validate it, returning
24+
//! a [`Module`] that can be used to instantiate the module.
25+
//!
26+
//! ```rust
27+
//! use tinywasm::{Store, Module};
28+
//!
29+
//! // Load a module from bytes
30+
//! let wasm = include_bytes!("../../../examples/wasm/add.wasm");
31+
//! let module = Module::parse_bytes(wasm)?;
32+
//!
33+
//! // Create a new store
34+
//! // Stores are used to allocate objects like functions and globals
35+
//! let mut store = Store::default();
36+
//!
37+
//! // Instantiate the module
38+
//! // This will allocate the module and its globals into the store
39+
//! // and execute the module's start function.
40+
//! // Every ModuleInstance has its own ID space for functions, globals, etc.
41+
//! let instance = module.instantiate(&mut store)?;
42+
//!
43+
//! // Get a typed handle to the exported "add" function
44+
//! // Alternatively, you can use `instance.get_func` to get an untyped handle
45+
//! // that takes and returns WasmValue types
46+
//! let func = instance.get_typed_func::<(i32, i32), (i32,)>(&mut store, "add")?;
47+
//! let res = func.call(&mut store, (1, 2))?;
48+
//!
49+
//! assert_eq!(res, (3,));
50+
//! # Ok::<(), tinywasm::Error>(())
51+
//! ```
52+
//!
53+
//! ## Features
54+
//! - `std` (default): Enables the use of `std` and `std::io` for parsing from files and streams.
55+
//! - `logging` (default): Enables logging via the `log` crate.
56+
//! - `parser` (default): Enables the `tinywasm_parser` crate for parsing WebAssembly modules.
57+
//!
58+
//! ## No-std support
59+
//! TinyWasm supports `no_std` environments by disabling the `std` feature. This removes
60+
//! support for parsing from files and streams, but otherwise the API is the same.
61+
//! Additionally, you must use a nightly compiler as TinyWasm uses the `error_in_core` feature
62+
//! and have a `GlobalAlloc` implementation for allocating memory.
1463
1564
// compiler error when using no_std without nightly
1665
#[cfg(all(not(feature = "std"), not(nightly)))]
@@ -57,7 +106,10 @@ pub mod parser {
57106
pub use tinywasm_parser::*;
58107
}
59108

60-
pub use tinywasm_types::*;
109+
/// Re-export of [`tinywasm_types`].
110+
pub mod types {
111+
pub use tinywasm_types::*;
112+
}
61113

62114
#[cfg(test)]
63115
mod tests {

crates/tinywasm/src/runtime/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ mod value;
55
pub use stack::*;
66
pub(crate) use value::RawWasmValue;
77

8+
#[allow(rustdoc::private_intra_doc_links)]
89
/// A WebAssembly Runtime.
910
///
1011
/// Generic over `CheckTypes` to enable type checking at runtime.
@@ -13,6 +14,6 @@ pub(crate) use value::RawWasmValue;
1314
///
1415
/// See <https://webassembly.github.io/spec/core/exec/runtime.html>
1516
///
16-
/// Execution is implemented in the [`crate::runtime::executer`] module
17+
/// Execution is implemented in the [`crate::runtime::executor`] module
1718
#[derive(Debug, Default)]
1819
pub struct DefaultRuntime {}

crates/tinywasm/src/store.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ impl FunctionInstance {
9898

9999
#[derive(Debug, Default)]
100100
/// Global state that can be manipulated by WebAssembly programs
101-
pub struct StoreData {
101+
pub(crate) struct StoreData {
102102
pub(crate) funcs: Vec<Rc<FunctionInstance>>,
103103
// pub tables: Vec<TableAddr>,
104104
// pub mems: Vec<MemAddr>,

crates/types/src/lib.rs

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
#![no_std]
2+
#![forbid(unsafe_code)]
3+
#![doc(test(
4+
no_crate_inject,
5+
attr(
6+
deny(warnings, rust_2018_idioms),
7+
allow(dead_code, unused_assignments, unused_variables)
8+
)
9+
))]
10+
#![warn(missing_debug_implementations, rust_2018_idioms, unreachable_pub)]
11+
12+
//! Types used by [`tinywasm`](https://docs.rs/tinywasm) and [`tinywasm_parser`](https://docs.rs/tinywasm_parser).
13+
114
extern crate alloc;
215

316
// log for logging (optional).
@@ -15,15 +28,29 @@ extern crate alloc;
1528
mod instructions;
1629
use core::fmt::Debug;
1730

31+
use alloc::boxed::Box;
1832
pub use instructions::*;
1933

34+
/// A TinyWasm WebAssembly Module
35+
///
36+
/// This is the internal representation of a WebAssembly module in TinyWasm.
37+
/// TinyWasmModules are validated before being created, so they are guaranteed to be valid (as long as they were created by TinyWasm).
38+
/// This means you should not trust a TinyWasmModule created by a third party to be valid.
2039
#[derive(Debug)]
2140
pub struct TinyWasmModule {
41+
/// The version of the WebAssembly module.
2242
pub version: Option<u16>,
43+
44+
/// The start function of the WebAssembly module.
2345
pub start_func: Option<FuncAddr>,
2446

47+
/// The functions of the WebAssembly module.
2548
pub funcs: Box<[Function]>,
49+
50+
/// The types of the WebAssembly module.
2651
pub types: Box<[FuncType]>,
52+
53+
/// The exports of the WebAssembly module.
2754
pub exports: Box<[Export]>,
2855
// pub tables: Option<TableType>,
2956
// pub memories: Option<MemoryType>,
@@ -39,15 +66,20 @@ pub struct TinyWasmModule {
3966
#[derive(Clone, PartialEq, Copy)]
4067
pub enum WasmValue {
4168
// Num types
69+
/// A 32-bit integer.
4270
I32(i32),
71+
/// A 64-bit integer.
4372
I64(i64),
73+
/// A 32-bit float.
4474
F32(f32),
75+
/// A 64-bit float.
4576
F64(f64),
4677
// Vec types
4778
// V128(i128),
4879
}
4980

5081
impl WasmValue {
82+
/// Get the default value for a given type.
5183
pub fn default_for(ty: ValType) -> Self {
5284
match ty {
5385
ValType::I32 => Self::I32(0),
@@ -135,19 +167,8 @@ impl TryFrom<WasmValue> for f64 {
135167
}
136168
}
137169

138-
// impl TryFrom<WasmValue> for i128 {
139-
// type Error = ();
140-
141-
// fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
142-
// match value {
143-
// WasmValue::V128(i) => Ok(i),
144-
// _ => Err(()),
145-
// }
146-
// }
147-
// }
148-
149170
impl Debug for WasmValue {
150-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171+
fn fmt(&self, f: &mut alloc::fmt::Formatter<'_>) -> alloc::fmt::Result {
151172
match self {
152173
WasmValue::I32(i) => write!(f, "i32({})", i),
153174
WasmValue::I64(i) => write!(f, "i64({})", i),
@@ -159,6 +180,7 @@ impl Debug for WasmValue {
159180
}
160181

161182
impl WasmValue {
183+
/// Get the type of a [`WasmValue`]
162184
pub fn val_type(&self) -> ValType {
163185
match self {
164186
Self::I32(_) => ValType::I32,
@@ -173,12 +195,19 @@ impl WasmValue {
173195
/// Type of a WebAssembly value.
174196
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175197
pub enum ValType {
198+
/// A 32-bit integer.
176199
I32,
200+
/// A 64-bit integer.
177201
I64,
202+
/// A 32-bit float.
178203
F32,
204+
/// A 64-bit float.
179205
F64,
206+
/// A 128-bit vector.
180207
V128,
208+
/// A reference to a function.
181209
FuncRef,
210+
/// A reference to an external value.
182211
ExternRef,
183212
}
184213

@@ -187,9 +216,13 @@ pub enum ValType {
187216
/// See <https://webassembly.github.io/spec/core/syntax/types.html#external-types>
188217
#[derive(Debug, Clone, PartialEq)]
189218
pub enum ExternalKind {
219+
/// A WebAssembly Function.
190220
Func,
221+
/// A WebAssembly Table.
191222
Table,
223+
/// A WebAssembly Memory.
192224
Memory,
225+
/// A WebAssembly Global.
193226
Global,
194227
}
195228

@@ -212,15 +245,6 @@ pub type LocalAddr = Addr;
212245
pub type LabelAddr = Addr;
213246
pub type ModuleInstanceAddr = Addr;
214247

215-
/// A WebAssembly Export Instance.
216-
///
217-
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#export-instances>
218-
#[derive(Debug)]
219-
pub struct ExportInst {
220-
pub name: String,
221-
pub value: ExternVal,
222-
}
223-
224248
/// A WebAssembly External Value.
225249
///
226250
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#external-values>

crates/wasm-testsuite/lib.rs

Lines changed: 16 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//!
33
//! The testsuite is included as a git submodule and embedded into the binary.
44
//!
5-
//! Generated from https://github.com/WebAssembly/testsuite
5+
//! Generated from <https://github.com/WebAssembly/testsuite>
66
77
#![forbid(unsafe_code)]
88
#![doc(test(
@@ -22,18 +22,21 @@ use std::borrow::Cow;
2222
#[include = "*.wast"]
2323
struct Asset;
2424

25-
/// List of all proposals.
26-
/// This list is generated from the `proposals` folder in https://github.com/WebAssembly/testsuite
25+
/// List of all proposals. Used to filter tests.
26+
///
27+
/// Includes all proposals from <https://github.com/WebAssembly/testsuite/tree/master/proposals>
2728
#[rustfmt::skip]
2829
pub const PROPOSALS: &[&str] = &["annotations", "exception-handling", "memory64", "function-references", "multi-memory", "relaxed-simd", "tail-call", "threads", "extended-const", "gc"];
2930

3031
/// Get all test file names and their contents.
31-
///
32-
/// Proposals can be filtered by passing a list of proposal names.
33-
/// Valid proposal names are listed in [`PROPOSALS`].
34-
/// Returns an iterator over tuples of the form `(test_name, test_data)`.
35-
/// test_name is the name of the test file and the proposal name (if any), e.g. `annotations/br.wast`.
36-
pub fn get_tests(include_proposals: &[String]) -> impl Iterator<Item = (String, Cow<'static, [u8]>)> {
32+
pub fn get_tests_wast(include_proposals: &[String]) -> impl Iterator<Item = (String, Cow<'static, [u8]>)> {
33+
get_tests(&include_proposals)
34+
.filter_map(|name| Some((name.clone(), get_test_wast(&name)?)))
35+
.map(|(name, data)| (name, Cow::Owned(data.to_vec())))
36+
}
37+
38+
/// Get all test file names.
39+
pub fn get_tests(include_proposals: &[String]) -> impl Iterator<Item = String> {
3740
let include_proposals = include_proposals.to_vec();
3841

3942
Asset::iter().filter_map(move |x| {
@@ -45,27 +48,19 @@ pub fn get_tests(include_proposals: &[String]) -> impl Iterator<Item = (String,
4548

4649
if proposal.map_or(false, |p| include_proposals.contains(&p.to_string())) {
4750
let full_path = format!("{}/{}", proposal.unwrap_or_default(), test_name);
48-
let data = Asset::get(&x).unwrap().data;
49-
Some((full_path, data))
51+
Some(full_path)
5052
} else {
5153
None
5254
}
5355
}
54-
Some(test_name) => {
55-
let data = Asset::get(&x).unwrap().data;
56-
Some((test_name.to_owned(), data))
57-
}
56+
Some(test_name) => Some(test_name.to_owned()),
5857
None => None,
5958
}
6059
})
6160
}
6261

6362
/// Get the WAST file as a byte slice.
64-
///
65-
/// # Examples
66-
/// proposals: {proposal}/{test_name}.wast
67-
/// tests: {test_name}.wast
68-
pub fn get_wast(name: &str) -> Option<Cow<'_, [u8]>> {
63+
pub fn get_test_wast(name: &str) -> Option<Cow<'static, [u8]>> {
6964
if !name.ends_with(".wast") {
7065
panic!("Expected .wast file. Got: {}", name);
7166
}
@@ -94,19 +89,7 @@ mod tests {
9489

9590
let proposal = proposal.split('/').nth(1).unwrap();
9691
unique_proposals.insert(proposal.to_owned());
97-
// assert!(PROPOSALS.contains(&proposal));
92+
assert!(PROPOSALS.contains(&proposal));
9893
}
99-
println!("{:?}", unique_proposals);
100-
}
101-
102-
#[test]
103-
fn test_get_tests() {
104-
let tests = get_tests(&["annotations".to_owned()]);
105-
let tests: Vec<_> = tests.collect();
106-
println!("{:?}", tests.iter().map(|(name, _)| name).collect::<Vec<_>>());
107-
108-
// for (name, data) in tests {
109-
// println!("{}: {}", name, data.len());
110-
// }
11194
}
11295
}

0 commit comments

Comments
 (0)