2021-11-13 02:52:35 -06:00
|
|
|
//! Frontend: convert Wasm to IR.
|
|
|
|
|
|
|
|
use crate::ir::*;
|
2021-11-13 02:56:49 -06:00
|
|
|
use anyhow::Result;
|
|
|
|
use log::trace;
|
2021-11-13 02:59:15 -06:00
|
|
|
use wasmparser::{ImportSectionEntryType, Parser, Payload, TypeDef};
|
2021-11-13 02:52:35 -06:00
|
|
|
|
|
|
|
pub fn wasm_to_ir(bytes: &[u8]) -> Result<Module> {
|
|
|
|
let mut module = Module::default();
|
2021-11-13 02:56:49 -06:00
|
|
|
let parser = Parser::new(0);
|
|
|
|
for payload in parser.parse_all(bytes) {
|
|
|
|
let payload = payload?;
|
|
|
|
handle_payload(&mut module, payload)?;
|
2021-11-13 02:52:35 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(module)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_payload<'a>(module: &mut Module, payload: Payload<'a>) -> Result<()> {
|
2021-11-13 02:56:49 -06:00
|
|
|
trace!("Wasm parser item: {:?}", payload);
|
2021-11-13 02:52:35 -06:00
|
|
|
match payload {
|
|
|
|
Payload::TypeSection(mut reader) => {
|
|
|
|
for _ in 0..reader.get_count() {
|
|
|
|
let ty = reader.read()?;
|
|
|
|
match ty {
|
|
|
|
TypeDef::Func(fty) => {
|
|
|
|
module.signatures.push(fty);
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-13 02:59:15 -06:00
|
|
|
Payload::ImportSection(mut reader) => {
|
|
|
|
for _ in 0..reader.get_count() {
|
|
|
|
match reader.read()?.ty {
|
|
|
|
ImportSectionEntryType::Function(sig_idx) => {
|
|
|
|
module.funcs.push(FuncDecl::Import(sig_idx as SignatureId));
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-13 02:52:35 -06:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|