Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Parser

The parser reads WebAssembly binary format incrementally.

Design

The parser is designed for streaming - it can parse modules larger than available memory by processing sections incrementally.

Interface

const Parser = parser_mod.Parser.init();

while (true) {
    const n = try reader.readSliceShort(pending_buf[pending_len..]);
    const eof = n == 0;
    var input = pending_buf[0 .. pending_len + n];

    while (true) {
        switch (parser.parse(input, eof)) {
            .parsed => |result| {
                // Handle payload
                switch (result.payload) {
                    .module_header => |header| { /* ... */ },
                    .func => |func| { /* ... */ },
                    .code_section => |code| { /* ... */ },
                    else => {},
                }
                input = input[result.consumed..];
            },
            .need_more_data => {
                // Buffer remaining data and read more
                break;
            },
            .end => return,
            .err => |e| return e,
        }
    }
}

Payloads

The parser emits payloads for each parsed element:

PayloadDescription
module_headerModule magic and version
type_sectionFunction types
import_sectionImports
func_sectionFunction declarations
code_sectionFunction bodies
data_sectionData segments
elem_sectionElement segments
global_sectionGlobals
memory_sectionMemories
table_sectionTables
export_sectionExports
start_sectionStart function

Validation

wasmz does not implement a full validator. Use external tools to validate WASM modules:

Basic sanity checks are performed during parsing (e.g., section structure, index bounds).

Memory Model

The parser allocates:

  • Payload data - Temporary, freed after handling
  • Module metadata - Types, imports, exports (owned by Module)

Key Files

FilePurpose
src/parser/root.zigParser implementation
src/parser/payload.zigPayload types
src/parser/range.zigSource ranges for debugging
src/parser/helper.zigParsing utilities

Parallel Compilation

The parser can trigger parallel compilation:

// For each code section, after parsing body:
// 1. validate body
// 2. lower body (compile to register machine)
// These can run in separate threads

Extension Proposals

New proposals are handled by:

  1. Adding new payload types
  2. Adding new opcodes to the compiler
  3. Adding new validation rules