use anyhow::{Result, bail, ensure};
pub use wasmparser::FunctionBody;
use super::Ind;
use crate::index::{FuncTypeId, IdVec, InputFuncId};
#[derive(Debug)]
pub enum InputFunction<'a> {
Import {},
Defined(FunctionBody<'a>),
}
#[derive(Debug, Clone)]
pub struct FunctionWithBody<'a> {
pub type_id: FuncTypeId,
pub body: FunctionBody<'a>,
}
#[derive(Debug, Default)]
pub struct CodeSection<'a> {
pub start_func: Option<InputFuncId>,
pub defined_funcs: IdVec<FunctionWithBody<'a>>,
}
impl<'a> CodeSection<'a> {
pub fn new(
start: Option<InputFuncId>,
funcs: Vec<FunctionBody<'a>>,
func_types: Vec<FuncTypeId>,
code_header: Option<(usize, usize, u32)>,
) -> Result<Ind<Self>> {
let Some((code_start, section_index, count)) = code_header else {
bail!("No code section start");
};
ensure!(
count as usize == funcs.len(),
"Function count mismatch: {} != {}",
count,
funcs.len()
);
ensure!(
count as usize == func_types.len(),
"Function types count mismatch: {} != {}",
count,
func_types.len()
);
Ok(Ind {
starting_offset: code_start,
section_index,
section_payload: CodeSection {
start_func: start,
defined_funcs: funcs
.into_iter()
.zip(&func_types)
.map(|(body, ty)| FunctionWithBody { type_id: *ty, body })
.collect(),
},
})
}
}