1use crate::TypeId;
2use crate::{FuncId, WasmInterfaceTypes, WitIdsToIndices, WitIndicesToIds};
3use anyhow::Result;
4use id_arena::{Arena, Id};
5
6#[derive(Debug, Default)]
7pub struct Imports {
8 arena: Arena<Import>,
9}
10
11#[derive(Debug)]
12pub struct Import {
13 id: ImportId,
14 pub func: FuncId,
15 pub module: String,
16 pub name: String,
17}
18
19pub type ImportId = Id<Import>;
20
21impl WasmInterfaceTypes {
22 pub(crate) fn parse_imports(
23 &mut self,
24 imports: wit_parser::Imports,
25 wids: &mut WitIndicesToIds,
26 ) -> Result<()> {
27 for import in imports {
28 let import = import?;
29 let ty = wids.ty(import.ty)?;
30 let (func, _) = self.add_import_func(import.module, import.name, ty);
31 wids.funcs.push(func);
32 }
33 Ok(())
34 }
35
36 pub(crate) fn encode_imports(
37 &self,
38 writer: &mut wit_writer::Writer,
39 wids: &mut WitIdsToIndices,
40 ) {
41 let mut w = writer.imports(self.imports.arena.len() as u32);
42 for import in self.imports.iter() {
43 let ty = self.funcs.get(import.func).ty;
44 w.add(&import.module, &import.name, wids.ty(ty));
45 wids.push_func(import.func);
46 }
47 }
48
49 pub fn add_import_func(&mut self, module: &str, name: &str, ty: TypeId) -> (FuncId, ImportId) {
50 let func = self.funcs.add_import(ty, self.imports.arena.next_id());
51 (func, self.imports.add(module, name, func))
52 }
53}
54
55impl Imports {
56 pub fn get(&self, id: ImportId) -> &Import {
58 &self.arena[id]
59 }
60
61 pub fn get_mut(&mut self, id: ImportId) -> &mut Import {
63 &mut self.arena[id]
64 }
65
66 pub fn iter(&self) -> impl Iterator<Item = &Import> {
76 self.arena.iter().map(|(_, f)| f)
77 }
78
79 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Import> {
81 self.arena.iter_mut().map(|(_, f)| f)
82 }
83
84 pub fn add(&mut self, module: &str, name: &str, func: FuncId) -> ImportId {
86 self.arena.alloc_with_id(|id| Import {
87 id,
88 module: module.to_string(),
89 name: name.to_string(),
90 func,
91 })
92 }
93}
94
95impl Import {
96 pub fn id(&self) -> ImportId {
98 self.id
99 }
100}