Module wast::parser

source · []
Expand description

Traits for parsing the WebAssembly Text format

This module contains the traits, abstractions, and utilities needed to define custom parsers for WebAssembly text format items. This module exposes a recursive descent parsing strategy and centers around the Parse trait for defining new fragments of WebAssembly text syntax.

The top-level parse function can be used to fully parse AST fragments:

use wast::Wat;
use wast::parser::{self, ParseBuffer};

let wat = "(module (func))";
let buf = ParseBuffer::new(wat)?;
let module = parser::parse::<Wat>(&buf)?;

and you can also define your own new syntax with the Parse trait:

use wast::{kw, Import, Func};
use wast::parser::{Parser, Parse, Result};

// Fields of a WebAssembly which only allow imports and functions, and all
// imports must come before all the functions
struct OnlyImportsAndFunctions<'a> {
    imports: Vec<Import<'a>>,
    functions: Vec<Func<'a>>,
}

impl<'a> Parse<'a> for OnlyImportsAndFunctions<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        // While the second token is `import` (the first is `(`, so we care
        // about the second) we parse an `ast::ModuleImport` inside of
        // parentheses. The `parens` function here ensures that what we
        // parse inside of it is surrounded by `(` and `)`.
        let mut imports = Vec::new();
        while parser.peek2::<kw::import>() {
            let import = parser.parens(|p| p.parse())?;
            imports.push(import);
        }

        // Afterwards we assume everything else is a function. Note that
        // `parse` here is a generic function and type inference figures out
        // that we're parsing functions here and imports above.
        let mut functions = Vec::new();
        while !parser.is_empty() {
            let func = parser.parens(|p| p.parse())?;
            functions.push(func);
        }

        Ok(OnlyImportsAndFunctions { imports, functions })
    }
}

This module is heavily inspired by syn so you can likely also draw inspiration from the excellent examples in the syn crate.

Structs

An immutable cursor into a list of tokens.

A helpful structure to perform a lookahead of one token to determine what to parse.

A low-level buffer of tokens which represents a completely lexed file.

An in-progress parser for the tokens of a WebAssembly text file.

Traits

A trait for parsing a fragment of syntax in a recursive descent fashion.

A trait for types which be used to “peek” to see if they’re the next token in an input stream of Parser.

Functions

A top-level convenience parseing function that parss a T from buf and requires that all tokens in buf are consume.

Type Definitions

A convenience type definition for Result where the error is hardwired to Error.